对象的构造函数属性

问题描述 投票:1回答:1

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

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的输出,这有点令人困惑,因为构造函数属性应该返回Rabbit,因为r是通过使用new运算符调用Rabbit创建的。

另外,如果我在分配原型之前调用Rabbit函数,它会给我所需的结果。

javascript prototype
1个回答
5
投票

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

Rabbit.prototype = new Animal();

这会调用Animal创建一个新实例,并将该实例指定为Rabbit.prototype。所以它的constructor,继承自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作为其原型的新对象,并将其放在Rabbit.prototype上。
  2. 我们在我们分配给constructor的新对象上设置了Rabbit.prototype
  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);
© www.soinside.com 2019 - 2024. All rights reserved.