【问题标题】:Why create a temporary constructor when doing Javascript inheritance?为什么在进行 Javascript 继承时要创建临时构造函数?
【发布时间】: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


【解决方案1】:

如果parentCtor 有一些初始化代码,并且在最坏的情况下需要一些参数,那么代码可能会意外失败。这就是他们创建一个虚拟函数并从中继承的原因。

【讨论】:

    【解决方案2】:

    关于使用对文字对象实例的引用,它通过插入另一个函数实例将 childCtor 的原型与 parentCtor 原型的实际实例解耦。

    【讨论】:

      【解决方案3】:

      thefourtheye 几乎回答了这个问题。第一个被认为更有效,但如果在初始化期间只创建一个临时构造函数,而不是在每次调用 inherits 时创建一个,则可以提高效率:

      goog.inherits = (function() {
        function tempCtor(){}
        return function(childCtor, parentCtor) {
          tempCtor.prototype = parentCtor.prototype;
          childCtor.superClass_ = parentCtor.prototype;
          childCtor.prototype = new tempCtor();
          childCtor.prototype.constructor = childCtor;
        };
      }());
      

      我怀疑这种差异是可测量的,它只是给你一种温暖的内在光芒,以不时节省几个 CPU 周期和内存字节。

      【讨论】: