gpt4 book ai didi

javascript - goog.inherits 使用临时构造函数有什么好处?

转载 作者:行者123 更新时间:2023-11-30 13:04:24 26 4
gpt4 key购买 nike

来自 Google 的 Closure 库:

goog.inherits = function(childCtor, parentCtor) {
/** @constructor */
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
/** @override */
childCtor.prototype.constructor = childCtor;
};

创建的临时构造函数有什么好处?

代码不只是这样的原因是什么:

goog.inherits = function(childCtor, parentCtor) {
/** @constructor */
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new parentCtor();
/** @override */
childCtor.prototype.constructor = childCtor;
};

最佳答案

第一个片段没有调用 parentCtor - 它没有通过调用构造函数来实例化一个对象,它只是继承自 parentCtor.prototype - 实际上它是Object.create 的解决方法(非常旧的浏览器不支持它)。另见 Understanding Crockford's Object.create shim关于 tempCtor 的工作原理和 What is the reason [not] to use the 'new' keyword here?关于调用 parent 的不可取性。

关于javascript - goog.inherits 使用临时构造函数有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224536/

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