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

JavaScript this issue with parent and child classes/objects

本文关键字:对象 问题 子类 父类 JavaScript      更新时间:2023-09-26

我不太确定如何用语言解释它,所以这里有一些示例代码来展示我试图实现的目标:

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

当我打印Car.wheels时,我会得到一个空数组。我想这是因为这辆车超出了范围。我认为我可能设计得完全错误,因为我没有太多地使用JavaScript类和对象。

你说得对。wheelsPerCar不在车上,它在工厂里。

您可以将this.wheelsPerCar = 4;更改为var wheelsPerCar = 4;,然后只使用wheelsPerCar而不使用this,它将在范围内。

carFactory实例和car实例没有父子关系。它们是一起定义的,但没有类继承。

您可以通过两种方式将wheelsPerCar属性公开给内部car实例:

  1. carFactory的一个实例传递给car构造函数
  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中阅读这个Scope和this。此外,您应该能够使用任何浏览器对此进行调试。