javascript中的原型继承问题 [英] Prototypal inheritance question in javascript
问题描述
我理解什么是原型继承,但我必须对实现感到困惑。我认为修改函数构造函数的原型会影响该构造函数的所有实例,但事实并非如此。 JS如何从对象查找方法到其原型?
I understand what prototypal inheritance is all about, but I must be confused as to the implementation. I thought that modifying a function constructor's prototype would affect all instances of that constructor, but this isn't the case. How does JS do the method lookup from an object to its prototype?
这是一个例子
function A(name){
this.name = name;
}
a = new A("brad");
A.prototype = {
talk: function(){
return "hello " + this.name;
}
}
a.talk() // doesn't work
b = new A("john");
b.talk() // works
我的印象是 a
会在 A
的原型中寻找方法 talk()
,所以在实例化 a
之前或之后对 A
的原型进行的任何修改都会被反映出来,但是这并没有似乎是这样的。有人可以帮我解释一下吗?
I was under the impression that a
would look for the method talk()
in A
's prototype, so any modification to A
's prototype, before or after a
was instantiated would be reflected, but this doesn't seem to be the case. Can someone explain this for me?
推荐答案
这是修改和替换<之间的区别/ strong>原型。
It's the difference between modifying and replacing the prototype.
function A(name){
this.name = name;
}
a = new A("brad");
// Change, don't replace.
A.prototype.talk = function(){
return "hello " + this.name;
};
a.talk() // works
b = new A("john");
b.talk() // works
以下是发生的事情:
Here is what is going on:
// Continued from above
var old_proto = A.prototype;
// Nuke that proto
A.prototype = {
talk: function() {
return "goodbye " + this.name;
}
};
var c = new A("Al");
a.talk() // hello brad
b.talk() // hello john
c.talk() // goodbye Al
old_proto.say_goodbye = function() {
return "goodbye " + this.name;
};
a.say_goodbye() // goodbye brad
b.say_goodbye() // goodbye john
c.say_goodbye() // TypeError c.say_goodbye is not a function.
这篇关于javascript中的原型继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!