繁体   English   中英

JavaScript父级和子级类/对象的此问题

[英]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实例:

  1. carFactory的实例carFactorycar构造函数。
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM