【问题标题】:Why set prototype's constructor to its constructor function? [duplicate]为什么要将原型的构造函数设置为其构造函数? [复制]
【发布时间】:2012-03-09 17:38:12
【问题描述】:

关于这个脚本的一行:

function Vehicle(hasEngine, hasWheels) {
    this.hasEngine = hasEngine || false;
    this.hasWheels = hasWheels || false;
}

function Car (make, model, hp) {
    this.hp = hp;
    this.make = make;
    this.model = model;
}

Car.prototype = new Vehicle(true, true);
Car.prototype.constructor = Car; 
Car.prototype.displaySpecs = function () {
    console.log(this.make + ", " + this.model + ", " + this.hp + ", " + this.hasEngine + ", " + this.hasWheels);
}

var myAudi = new Car ("Audi", "A4", 150);
myAudi.displaySpecs(); // logs: Audi, A4, 150, true, true

我的问题是:什么是

Car.prototype.constructor = Car;  

做吗?更重要的是,不这样做会有什么后果,在什么情况下最有用?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    它恢复了您覆盖的原始原型对象上的.constructor 属性。人们恢复它是因为它预计会在那里。

    有些人喜欢做...

    if (my_obj.constructor === Car) { ... }
    

    这不是必需的,因为instanceof 是更好的 IMO 测试。

    if (my_obj instanceof Car) { ... }
    
    if (my_obj instanceof Vehicle) { ... }
    

    【讨论】:

      猜你喜欢
      • 2012-01-17
      • 2020-01-14
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多