javascript - 修改父构造函数不影响子
问题描述
在已经用于创建对象之后修改构造函数定义时,对象属性是否会被覆盖,就好像对象是自己重新创建的一样?类似于原型链在原型被修改时如何保持方法更新。
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?
解决方案
不要使用proto,因为它已被弃用,将原型与 Object.create 结合使用,例如:
SomeClass.prototype = Object.create(SomeOtherClass.prototype);
不要将方法放在构造函数中。通过这样做,将为每个实例创建该方法。将该方法放在原型上,以便成员可以共享它,例如
SomeClass.prototype.someMethod = () => {...}
当涉及到您的问题时,已经在其中一条评论中得到了回答。
推荐阅读
- javascript - React Hook 在 useEffect 中返回基值
- javascript - 需要帮助优化节点列表数组的突变观察者
- javascript - 更改并尝试进行一些调整时,元素数组在类中变得未定义
- r - 如何在 R 中制作队列预期寿命数据表?
- javascript - POST 请求获取正文的服务工作者获取事件
- python - 在一张图中绘制多条线
- python - Pygame [AI 汽车模型视觉] 中遮罩和发射光束之间的重叠
- java - 为什么我的 Android 套接字服务器在我的客户端触发套接字错误 10061
- python - Python:查找形状为 i,j,k 的数组中每个 i,j 组合的 k 方向最大值的位置
- javascript - 向 Flask 提交多个表单(400 BAD REQUEST)