关于这个脚本的一行:
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
Run Code Online (Sandbox Code Playgroud)
我的问题是:做什么
Car.prototype.constructor = Car;
Run Code Online (Sandbox Code Playgroud)
做?更重要的是,不这样做的后果是什么,在哪种情况下最有用?
小智 19
它恢复了.constructor您覆盖的原始原型对象上的属性.人们恢复它,因为它预计会在那里.
有些人喜欢......
if (my_obj.constructor === Car) { ... }
Run Code Online (Sandbox Code Playgroud)
这不是必需的,因为它instanceof是一个更好的测试IMO.
if (my_obj instanceof Car) { ... }
if (my_obj instanceof Vehicle) { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8269 次 |
| 最近记录: |