首页 > 解决方案 > 修改父构造函数不影响子

问题描述

在已经用于创建对象之后修改构造函数定义时,对象属性是否会被覆盖,就好像对象是自己重新创建的一样?类似于原型链在原型被修改时如何保持方法更新。

function ParentFunction(a){
this.a = a;
this.method = function(){console.log(this.name);}
}

var parent = {};
parent.__proto__ = ParentFunction.prototype;
ParentFunction.call(parent,1);

//child linking
var child = {};
child.__proto__ = parent; // child now has a and method


// changing parent constructor
parent.__proto__.constructor = function ParentFunction(a){
this.a = a;
this.method = function(){console.log("new");}
}

// this does not change child.method function. why not?

标签: javascript

解决方案


  1. 不要使用proto,因为它已被弃用,将原型与 Object.create 结合使用,例如:

    SomeClass.prototype = Object.create(SomeOtherClass.prototype);
    
  2. 不要将方法放在构造函数中。通过这样做,将为每个实例创建该方法。将该方法放在原型上,以便成员可以共享它,例如

    SomeClass.prototype.someMethod = () => {...}
    

当涉及到您的问题时,已经在其中一条评论中得到了回答。


推荐阅读