使用父类和子类/ JavaScript来解决此问题

时间:2015-03-23 03:22:11

标签: javascript

我不太确定如何用文字解释它,所以这里有一些示例代码来展示我想要实现的目标:

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类和对象。

3 个答案:

答案 0 :(得分:3)

你是对的。 wheelsPerCar不在车上,而是在工厂里。

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

答案 1 :(得分:0)

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

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

  1. carFactory的实例传递给car构造函数。
  2. 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。此外,您应该能够使用任何浏览器进行调试。