我在阅读原型(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.prototype
的 constructor
是不正确的,因为:
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;
}
三个变化:
- 我们在设置继承时不调用
Animal
,我们只是创建一个使用Animal.prototype
作为其原型(prototype)的新对象,并将其放在Rabbit.prototype
. - 我们在分配给
Rabbit.prototype
的新对象上设置constructor
。 - 我们在初始化实例时确实调用了
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/