gpt4 book ai didi

javascript - 修改父构造函数不会影响子构造函数

转载 作者:行者123 更新时间:2023-12-03 00:33:12 25 4
gpt4 key购买 nike

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

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?

最佳答案

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

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

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

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

关于javascript - 修改父构造函数不会影响子构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com