【发布时间】:2018-06-11 22:44:36
【问题描述】:
我在阅读原型时遇到了这个例子。
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 函数,它会给我想要的结果。
【问题讨论】:
-
在制作对象之前你必须做
Rabbit.prototype.constructor=Rabbit; -
在分配原型时,将构造函数更改为继承自
Animal的构造函数。 -
为什么会这样?构造函数是原型的属性还是对象的属性?
-
constructor继承自原型。 -
你现在明白为什么
r.constructor返回Animal了吗?
标签: javascript prototype