gpt4 book ai didi

javascript - 调用 Class.prototype = new MyClass() 是否确保每次都重新实例化父类(super class)?

转载 作者:行者123 更新时间:2023-12-02 07:01:16 25 4
gpt4 key购买 nike

我正在使用:

var ReportsServiceCall = function () { };

ReportsServiceCall.prototype = new ServiceCall();

使用这段代码,每次创建 new ReportsServiceCall 时,ServiceCall 都是一个新实例吗?我需要这样。

最佳答案

没有

如您所写,原型(prototype)仅设置一次。但是,这并不是一个很好的编写方式。

我会这样写

var ReportsServiceCall = function () {

// parent constructor; optional
ServiceCall.call(this);
};

// setup prototype; see comment below
ReportsServiceCall.prototype = Object.create(ServiceCall.prototype, {
constructor: {
value: ReportsServiceCall,
enumerable: false,
writable: true,
configurable: true
}
});

注意:除了设置 super_ 之外,这就是 node.js 在其 util.inherits 中进行 Vanilla 继承的方式。功能。

一旦您了解了它的工作原理,这是一种非常有效的技术。

关于javascript - 调用 Class.prototype = new MyClass() 是否确保每次都重新实例化父类(super class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20339172/

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