Javascript 为什么要设置原型';s构造函数到它的构造函数函数?
关于此脚本的一行:Javascript 为什么要设置原型';s构造函数到它的构造函数函数?,javascript,Javascript,关于此脚本的一行: 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
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
是一个更好的测试
if (my_obj instanceof Car) { ... }
if (my_obj instanceof Vehicle) { ... }