javascript原型继承混淆 [英] javascript prototypical inheritance confused
问题描述
给出实现这种继承的标准方法
given the standard way of achieving inheritance like this
function BaseClass() {
}
function SubClass() {
BaseClass.call(this);
}
SubClass.prototype = Object.create(BaseClass.prototype);
SubClass.prototype.constructor = SubClass;
为什么需要这样做
SubClass.prototype = Object.create(BaseClass.prototype);
并最终得到类似
function F(){}
F.prototype = BaseClass.prototype;
SubClass.prototype = new F();
而不是只做
Subclass.prototype = BaseClass.prototype;
推荐答案
为JavaScript中的事物赋值实际上只是复制引用(除非使用基本类型)。所以当你这样做时:
Assigning values to things in JavaScript really just copies a reference (unless working with primitive types). So when you do this:
Subclass.prototype = BaseClass.prototype;
你真正做的是分配<$ c的原型$ c> SubClass 到内存中与 BaseClass
原型相同的位置,因此您对所做的任何原型相关更改SubClass
也会影响 BaseClass
。这是一个小例子:
What you're really doing is assigning the prototype of SubClass
to the same location in memory as the prototype of BaseClass
, therefore any prototype related changes you make to SubClass
will also affect BaseClass
. Here's a little example:
function BaseClass() {
}
function SubClass() {
BaseClass.call(this);
}
SubClass.prototype = BaseClass.prototype;
SubClass.prototype.constructor = SubClass;
SubClass.prototype.subClassFunction = function(){
console.log("Added this to SubClass");
}
var baseObj = new BaseClass();
baseObj.subClassFunction(); // => "Added this to SubClass"
这就是你想要的原因使用
That's why you want to use
SubClass.prototype = Object.create(BaseClass.prototype);
因为它会创建 new 和 unique 使用指定原型的对象。
because it will create a new and unique object with the specified prototype instead.
您可以阅读有关此函数如何工作的更多信息 here 。
You can read more about how this function works here.
这篇关于javascript原型继承混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!