我在阅读原型时遇到了这个例子。
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函数,它会给我所需的结果。
对象从其原型(通常)继承constructor
;他们从构造函数的prototype
属性中获取原型,这些属性在创建时创建它们(如果它们是由构造函数创建的)。 Rabbit.prototype
的constructor
不正确,因为:
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;
}
有三个变化:
Animal
,我们只是创建一个使用Animal.prototype
作为其原型的新对象,并将其放在Rabbit.prototype
上。constructor
的新对象上设置了Rabbit.prototype
。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);