javascript - 对于 JavaScript 的继承,是引用父类的原型(prototype)还是复制父类的原型(prototype)更好?

标签 javascript inheritance prototype

目前我在我的 JavaScript 库中实现继承如下:

parent = function() { };
parent.prototype.hello = function() { alert('parent'); };

child = function() { };
child.prototype = parent.prototype;

但是,我注意到当我重写子“类”原型(prototype)中的函数时,它也意外地重写了父类的原型(prototype):

child.prototype.hello = function() { alert('child'); }

(new parent()).hello();  // alerts "child" --> undesirable
(new child()).hello();   // alerts "child" --> desirable

如果我从 child 的原型(prototype)中删除一些东西

delete child.prototype.hello;

那么父级的原型(prototype)就会受到不良影响。所以,也许

child.prototype = parent.prototype;

是不是实现继承的最佳方式?与其让子“类”引用父原型(prototype),不如将父原型(prototype)复制到子原型(prototype)更有意义?

_.extend(child.prototype, parent.prototype);

最佳答案

child.prototype = parent.prototype; 不正确,原因您已在问题中详细说明。

使用 _.extend也不是你想要的。考虑到“继承的”父原型(prototype)属性的变化不会导致子属性发生变化:

// perform extension
_.extend(child.prototype, parent.prototype);

// parent later gains new property after extension
parent.prototype.parentProp = function() { alert("new"); };

(new parent()).parentProp();  // alerts "new" --> desirable
(new child()).parentProp();   // error; doesn't exist --> undesirable

您可能需要 child.prototype = Object.create(parent.prototype); 这表示:“在 child.prototype 中存储一个新对象。这个新对象使用parent.prototype 对象作为它自己的原型(prototype)。”这会导致真正的继承发生,因为当 child 实例想要一个属性时,它首先查看自己的属性,然后查看其直接原型(prototype)(child.prototype),然后然后在其原型(prototype)的原型(prototype) (parent.prototype) 中。

原型(prototype)链

  • 当使用 child.prototype = parent.prototype 时,实例的原型(prototype)链如下所示:

    { child instance } ==> { only prototype }
    
    { parent instance } ==> { only prototype }
    

    其中 only prototypechild.prototypeparent.prototype 引用的共享对象。

  • 当使用_.extend(child.prototype, parent.prototype)时,子原型(prototype)和父原型(prototype)是不同的,但没有直接继承。更改父原型(prototype)根本不会更改子原型(prototype),因为我们只是在一个时间点将父原型(prototype)的属性复制到子原型(prototype)中。

    { child instance } ==> { child.prototype }
    
    { parent instance } ==> { parent.prototype }
    
  • 使用 child.prototype = Object.create(parent.prototype);,您实际上拥有从父原型(prototype)到子原型(prototype)的继承:

    { child instance } ==> { child.prototype } ==> { parent.prototype }
    
    { parent instance } ==> { parent.prototype }
    

关于javascript - 对于 JavaScript 的继承,是引用父类的原型(prototype)还是复制父类的原型(prototype)更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26978139/

相关文章:

javascript - Dijkstra 算法 - JavaScript 实现

javascript - 如果 PrimeFaces inputSwitch 在隐藏的 div 中,则无法正确显示

javascript - 页面加载后如何从 url 中删除查询字符串?

javascript - 辅助功能 (JAWS) - 带有 jQ​​uery 选择库的下拉列表

java - 为什么字段从父类打印,而方法从子类打印(Java)

php - 合并后代对象的数组属性

javascript - JavaScript 属性查找规则有哪些异常(exception)?

javascript - 为什么 process.__proto__ !== process.constructor.prototype ?

java - Spring Boot @requestmapping继承

javascript - 方法未添加到原型(prototype)