为什么要设置原型's构造函数转换为其构造函数函数

Why set prototype's constructor to its constructor function?

本文关键字:构造函数 转换 函数 设置 原型 为什么      更新时间:2023-09-26

关于这个脚本的一行:

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;  

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

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

有些人喜欢做…

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

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

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