我不太确定如何用文字解释它,所以这里有一些示例代码来展示我想要实现的目标:
function carFactory(){
this.wheelsPerCar = 4;
this.car = function() {
this.wheels = [];
this.addWheels = function(){
for(var i = 0; i < this.wheelsPerCar; i++){
var wheel = new this.wheel();
this.wheels.push(wheel);
}
};
this.wheel = function(){
};
};
};
var cf = new carFactory();
var myCar = new cf.car();
myCar.addWheels();
当我打印myCar.wheels时,我得到一个空数组。我想这是因为this.wheelsPerCar超出了范围。我认为我可能设计这个完全错误,因为我没有使用JavaScript类和对象。
答案 0 :(得分:3)
你是对的。 wheelsPerCar
不在车上,而是在工厂里。
您可以将this.wheelsPerCar = 4;
更改为var wheelsPerCar = 4;
,然后只使用wheelsPerCar
而不使用this
,它将在范围内。
答案 1 :(得分:0)
carFactory
实例和car
实例没有父子关系。它们是一起定义的,但那里没有类继承。
您可以通过两种方式将wheelsPerCar
属性公开给内部car
实例:
carFactory
的实例传递给car
构造函数。var wheelsPerCar = this.wheelsPerCar
范围内设置car
变量,以便在没有this
的情况下访问该变量。答案 2 :(得分:0)
this.addWheels = function(){
debugger;
for(var i = 0; i < this.wheelsPerCar; i++){
var wheel = new this.wheel();
this.wheels.push(wheel);
}
};
this.wheelsPerCar未定义,0&lt; undefined,评估为false。您想先阅读此Scope and this in JavaScript。此外,您应该能够使用任何浏览器进行调试。