目前我在JavaScript库中实现继承的方式如下:
parent = function() { };
parent.prototype.hello = function() { alert('parent'); };
child = function() { };
child.prototype = parent.prototype;
然而,我注意到当我在子“类”的原型中覆盖一个函数时,它会不希望地同时覆盖父级的原型:
child.prototype.hello = function() { alert('child'); }
(new parent()).hello(); // alerts "child" --> undesirable
(new child()).hello(); // alerts "child" --> desirable
如果我从子原型中删除了某些内容
delete child.prototype.hello;
那么,如果更改了父级的原型,则会产生不良影响。因此,也许
child.prototype = parent.prototype;
这种实现继承的方式不是最好的吗?也许将父原型对象复制到子原型对象中,比让子"类"引用父原型对象更有意义?
_.extend(child.prototype, parent.prototype);
child.prototype = parent.prototype;
正确的情况。你可能想要使用child.prototype = Object.create(parent.prototype);
。 - apsillersObject.create
进行继承。请参阅使用Object.create
进行继承的优势和https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance。 - Felix Kling