而不是这个:
SubBase.prototype = Base.prototype;
SubBase.prototype = {
subBaseFunction: function() {},
subBaseOtherFunction: function() {}
}
您需要将每个附加方法添加到现有原型对象中,以避免覆盖您刚刚放在那里的Base.prototype:
// establish the prototype we're inheriting from
// make a new object into the prototype so when we change it, it
// doesn't change the original
SubBase.prototype = Object.create(Base.prototype);
// now add more methods onto the inherited prototype
SubBase.prototype.subBaseFunction = function() {};
SubBase.prototype.subBaseOtherFunction = function() {};
注意:您也不想只分配Base.prototype,因为当您更改SubBase.prototype 时,您实际上会更改两个对象(对象分配只是一个参考)。所以在这里,我使用Object.create(Base.prototype) 来创建该原型的副本。
许多库支持某种extend() 函数,该函数将属性从一个对象复制到另一个对象。这使您可以定义一个单独的方法对象,然后将其“添加”到现有原型中,但此功能不是内置于普通 javascript 中。
例如在 jQuery 中,你可以这样做:
// establish the prototype we're inheriting from
SubBase.prototype = Object.create(Base.prototype);
jQuery.extend(SubBase.prototype, {
subBaseFunction: function() {},
subBaseOtherFunction: function() {}
});
或者,2016 年更新,ES6 包含一个Object.assign() function,它将属性从一个对象复制到另一个对象:
Object.assign(SubBase.prototype, {
subBaseFunction: function() {},
subBaseOtherFunction: function() {}
});
或者,您可以创建自己的函数,只需几行代码即可将属性从一个对象复制到另一个对象。
或者,用纯javascript编写相同的代码:
// copy properties from src to target
function copyProperties(target, src) {
for (var prop in src) {
if (src.hasOwnProperty(prop)) {
target[prop] = src[prop];
}
}
return(target);
}
// establish the prototype we're inheriting from
SubBase.prototype = Object.create(Base.prototype);
copyProperties(SubBase.prototype, {
subBaseFunction: function() {},
subBaseOtherFunction: function() {}
});
这是我通常使用的样式:
function Base() {
this.attribute1 = null;
}
Base.prototype = {
baseFunction: function() {}
};
function SubBase()
{
Base.apply(this, arguments); // Constructor call with arguments
}
(function() {
var proto = SubBase.prototype = Object.create(Base.prototype);
proto.constructor = SubBase;
proto.subBaseFunction = function() {
// code here
};
proto.subBaseOtherFunction = function() {
// code here
};
})();