简体   繁体   English

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

[英]JavaScript this issue with parent and child classes/objects

I'm not quite sure how to explain it in words so here is some example code to show what I'm trying to achieve: 我不太确定如何用语言解释它,因此这是一些示例代码来显示我要实现的目标:

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();

When I print myCar.wheels I get an empty array back. 当我打印myCar.wheels时,我得到一个空数组。 I think this is because this.wheelsPerCar is out of scope. 我认为这是因为this.wheelsPerCar不在范围内。 I think I'm likely designing this completely wrong as I haven't work much with JavaScript classes and objects. 我认为我可能会设计出完全错误的代码,因为我对JavaScript类和对象的使用还不多。

You're kind of right. 你是对的。 wheelsPerCar is not on the car, it's on the factory. wheelsPerCar不是在汽车上,而是在工厂里。

You could just change this.wheelsPerCar = 4; 您可以更改this.wheelsPerCar = 4; to be var wheelsPerCar = 4; var wheelsPerCar = 4; then just use wheelsPerCar without this and it will be in scope. 然后只使用不带this wheelsPerCar ,它将在范围内。

The carFactory instance and the car instance don't have a parent-child relationship. carFactory实例和car实例没有父子关系。 They're defined together, but there's no class inheritance there. 它们是一起定义的,但是那里没有类继承。

You could expose the wheelsPerCar property to the inner car instance in 2 ways: 您可以通过两种方式将wheelsPerCar属性公开给内部car实例:

  1. Pass an instance of carFactory to the car constructor function. carFactory的实例carFactorycar构造函数。
  2. Set a var wheelsPerCar = this.wheelsPerCar variable in the car scope so it can access it without the this . 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 is undefined, 0 < undefined, evaluate as false. this.wheelsPerCar未定义,0 <未定义,评估为false。 You want to read this Scope and this in JavaScript first. 您首先要在JavaScript中阅读此作用域和内容 Also, you should be able to debug this with any browser. 另外,您应该能够使用任何浏览器进行调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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