为什么将prototype的构造函数设置为其构造函数? [英] Why set prototype's constructor to its constructor function?

查看:69
本文介绍了为什么将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;  

吗?更重要的是,不这样做的后果是什么,以及哪种情况最有用呢?

do? More importantly, what are the consequences of not doing this, and in which circumstances is it MOST useful?

推荐答案

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

It restores the .constructor property that was on the original prototype object that you overwrote. People restore it because it's expected to be there.

有些人喜欢这样做...

Some people like to do...

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

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

This isn't required, since instanceof is a better test IMO.

if (my_obj instanceof Car) { ... }

if (my_obj instanceof Vehicle) { ... }

这篇关于为什么将prototype的构造函数设置为其构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆