Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在执行Javascript继承时创建临时构造函数?_Javascript_Prototype_Google Closure Library - Fatal编程技术网

为什么在执行Javascript继承时创建临时构造函数?

为什么在执行Javascript继承时创建临时构造函数?,javascript,prototype,google-closure-library,Javascript,Prototype,Google Closure Library,为什么Google Closure库中的内容看起来像这样: goog.inherits = function(childCtor, parentCtor) { function tempCtor() {}; tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); childCtor

为什么Google Closure库中的内容看起来像这样:

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;
};

temptor
提供了什么好处?

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

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

第四,他们基本上回答了这个问题。第一个被视为效率稍高一些,但如果在初始化期间只创建一个临时构造函数,而不是每次调用继承时创建一个临时构造函数,则可以提高效率:


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

两者都在childCtor实例的继承链上添加了一个无用的对象。在第一种情况下,该对象是空函数对象。在第二个实例中,它是一个完整的parentCtor实例。因此,可以认为第一个函数更有效(尽管它每次都创建一个新的空函数,而只需要一个)-
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;
  };
}());