我正在尝试创建一个Dog通过类的原型继承继承的新Animal类:
function Animal() {
this.name = "animal";
this.writeName = function() {
document.write(this.name);
}
}
function Dog() {
this.name = "dog";
this.prototype = new Animal();
}
new Dog().writeName()
Run Code Online (Sandbox Code Playgroud)
但是,我收到一个Javascript错误:Uncaught TypeError: Object #<Dog> has no method 'say'.
为什么?Dog对象不应该将对象保留Animal为原型吗?
function Animal() {
this.name = "animal";
this.writeName = function() {
document.write(this.name);
}
}
function Dog() {
this.name = "dog";
}
Dog.prototype = new Animal();
dog = new Dog();
dog.writeName();
Run Code Online (Sandbox Code Playgroud)
现在狗拥有动物的所有属性.
@ryan 的答案当然是正确的,但他并没有真正说出它有什么不同,而且对于初学者来说可能不清楚,所以......
您所犯的错误是将this.prototype = new Animal();一个实例分配给在当前实例Animal上命名的属性(由 引用),但是在此上下文中命名的属性没有什么特别的。prototypeDog thisprototype
该prototype属性仅对函数对象有效。当您SomeFunc使用new SomeFunc()该新对象的内部/隐藏[[prototype]]指针创建一个新实例时,将引用 指向的对象SomeFunc.prototype。这个prototype名字在任何其他上下文中都没有特殊之处。
| 归档时间: |
|
| 查看次数: |
495 次 |
| 最近记录: |