2

ia have a problem. How can i get access to my vars in TeslaModelS from the prototype extension ?

Or is my Plugin-Pattern wrong ?

I would like to separate the different areas of my app and not have it all in one big file

var TeslaModelS = function () {
    this.numWheels = 4;
    this.manufacturer = 'Tesla';
    this.make = 'Model S';

    this.Drive.pressGasPedal();
}

TeslaModelS.prototype = function () {
    var _this = this;

    var Drive = {
        go: function () {
          // HOW CAN I GET RED AND WRITE ACCESS TO MY VARS IN TeslaModelS ??
            console.log(_this.numWheels)
        },

        stop: function () {
        }
    }

    return {
        Drive: {
            pressBrakePedal: Drive.stop,
            pressGasPedal: Drive.go
        }
    }

}();

var i = new TeslaModelS();
DerMakkuz
  • 133
  • 2
  • 11

1 Answers1

2

You can't, with the structure you've created. I would suggest using a more normal structure:

// The constructor function
var TeslaModelS = function() {
  this.numWheels = 4;
  this.manufacturer = 'Tesla';
  this.make = 'Model S';

  this.pressGasPedal();
};

TeslaModelS.prototype.pressGasPedal = function() {
  console.log(this.numWheels);
};

TeslaModelS.prototype.pressBrakePedal = function() {
};

var i = new TeslaModelS();

But if you don't want to, if you really want that Drive object, you'll need to create bound versions of those functions on a distinct Drive object for each instance:

// The functions you'll bind each time
var Drive = {
  go: function() {
    console.log(this.numWheels)
  },

  stop: function() {}
};

// The constructor function
var TeslaModelS = function() {
  this.numWheels = 4;
  this.manufacturer = 'Tesla';
  this.make = 'Model S';

  // Create a Drive object for this instance with the functions bound
  // to `this`
  this.Drive = {
    pressGasPedal: Drive.go.bind(this),
    pressBrakePedal: Drive.stop.bind(this)
  };

  this.Drive.pressGasPedal();
}

var i = new TeslaModelS();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Hm... i really want it because i want to seperate my application with this a little bit more. This bound thing is way complicated isnt it ? is there no other pattern which i can use ? – DerMakkuz Sep 16 '16 at 10:12
  • @DerMakkuz: It's not that complicated. It was complicated a bit by the fact you've used different names for the properties (`pressGasPedal` vs. `go`), but you could use a loop to create the bound functions. But consider, what if I do `var t1 = new TeslaModelS(); var t2 = new TeslaModelS(); t1.Drive = t2.Drive;` Now we've got weird cross-talk. That's why I would stick to a normal pattern (not to mention being well-supported by tools, dramatically simpler syntax if you use ES2015 [transpiling if necessary], etc.). – T.J. Crowder Sep 16 '16 at 10:15