[英]JavaScript inheritance issue inconsistency (single instance of parent for all child objects…or not?)
[英]JavaScript this issue with parent and child classes/objects
我不太确定如何用语言解释它,因此这是一些示例代码来显示我要实现的目标:
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类和对象的使用还不多。
你是对的。 wheelsPerCar
不是在汽车上,而是在工厂里。
您可以更改this.wheelsPerCar = 4;
是var wheelsPerCar = 4;
然后只使用不带this
wheelsPerCar
,它将在范围内。
carFactory
实例和car
实例没有父子关系。 它们是一起定义的,但是那里没有类继承。
您可以通过两种方式将wheelsPerCar
属性公开给内部car
实例:
carFactory
的实例carFactory
给car
构造函数。 car
范围内设置一个var wheelsPerCar = this.wheelsPerCar
变量,这样它就可以在没有this
情况下访问它。 this.addWheels = function(){
debugger;
for(var i = 0; i < this.wheelsPerCar; i++){
var wheel = new this.wheel();
this.wheels.push(wheel);
}
};
this.wheelsPerCar未定义,0 <未定义,评估为false。 您首先要在JavaScript中阅读此作用域和内容 。 另外,您应该能够使用任何浏览器进行调试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.