【发布时间】:2025-12-15 03:10:01
【问题描述】:
为什么来自 Google Closure 库的 goog.inherits 看起来像这样:
goog.inherits = function(childCtor, parentCtor) {
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
};
而不是
goog.inherits = function(childCtor, parentCtor) {
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new parentCtor();
childCtor.prototype.constructor = childCtor;
};
tempCtor 有什么好处?
【问题讨论】:
-
两者都在 childCtor 实例的继承链上添加了一个无用的对象。在第一种情况下,该对象是一个空函数对象。第二个,它是一个完整的 parentCtor 实例。所以第一个可以被视为更有效(尽管它每次都会创建一个新的空函数,而只有一个是必需的)。
-
这是一篇有趣的文章 - bolinfest.com/javascript/inheritance.php
标签: javascript prototype google-closure-library