我有一个问题。如何从原型扩展中访问TeslaModelS中的我的变量?
或者我的插件模式错了吗?
我想将我的应用的不同区域分开,而不是将其全部放在一个大文件中
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();

答案 0 :(得分:3)
您无法使用您创建的结构。我建议使用更正常的结构:
// 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();

但是如果你不想,如果你真的想要那个Drive
对象,你需要在不同的Drive
对象上创建这些函数的绑定版本。实例:
// 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();