javascript - 对象的构造函数属性

标签 javascript prototype

我在阅读原型(prototype)时遇到了这个例子。

function Animal(){
    this.name = 'Animal'
}

var animal1 = new Animal();

function Rabbit(){
    this.canEat = true;
}

Rabbit.prototype = new Animal();

var r = new Rabbit();

console.log(r.constructor)

控制台给我 Animal 作为 r.constructor 的输出,这有点令人困惑,因为 constructor 属性应该返回 Rabbit,因为 r 是通过使用 new 运算符调用 Rabbit 创建的。

另外,如果我在分配原型(prototype)之前调用 Rabbit 函数,它会给我想要的结果。

最佳答案

对象从它们的原型(prototype)继承constructor(通常);它们从构造函数的 prototype 属性中获取原型(prototype),该构造函数在创建它们时创建它们(如果它们是由构造函数创建的)。 Rabbit.prototypeconstructor 是不正确的,因为:

Rabbit.prototype = new Animal();

调用 Animal 创建一个新实例,并将该实例分配为 Rabbit.prototype。所以它的构造函数,继承自Animal.prototype,是Animal。您已经替换了 Rabbit.prototype 上的默认对象(constructor 设置为 Rabbit ).

一般来说,Rabbit.prototype = new Animal() 并不是设置继承的最佳方式。相反,您可以这样做:

Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;

然后在 Rabbit 中:

function Rabbit() {
    Animal.call(this);    // ***
    this.name = "Rabbit"; // Presumably we want to change Animal's deafult
    this.canEat = true;
}

三个变化:

  1. 我们在设置继承时不调用Animal,我们只是创建一个使用Animal.prototype作为其原型(prototype)的新对象,并将其放在Rabbit.prototype.
  2. 我们在分配给 Rabbit.prototype 的新对象上设置 constructor
  3. 我们在初始化实例时确实调用了Animal(在Rabbit中)。

实例:

function Animal(){
    this.name = 'Animal'
}

var animal1 = new Animal();

function Rabbit() {
    Animal.call(this);    // ***
    this.name = "Rabbit"; // Presumably we want to change Animal's deafult
    this.canEat = true;
}

Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;


var r = new Rabbit();
console.log(r.constructor);


或者,当然,使用 ES2015+ class 语法,它会为您处理这个管道(以及其他一些好处)。

class Animal {
    constructor() {
        this.name = "Animal";
    }
}

class Rabbit extends Animal {
    constructor() {
        super();
        this.name = "Rabbit";
        this.canEat = true;
    }
}

const r = new Rabbit();
console.log(r.constructor);

关于javascript - 对象的构造函数属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48057386/

相关文章:

JavaScript:为什么要获取最后插入的值?

javascript - PapaParse 不起作用(返回空数组)

javascript - 数据完全渲染时的 React/Meteor 初始化函数

javascript - Spring模板中访问验证失败的字段名称

javascript - 访问 Javascript 原型(prototype)函数

JavaScript 原型(prototype)函数问题

当我将参数设置为对象时,JavaScript 返回 TypeError

javascript - 强制 Android 浏览器每秒重绘

javascript - jquery可以做到这一点吗?

javascript - 哪个原型(prototype)用于创建带有未知标签的节点