Domanda

Why does goog.inherits from the Google Closure Library look like this:

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

rather than

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

What benefit does tempCtor provide?

È stato utile?

Soluzione

If parentCtor had some initialization code, and in the worst case expecting some arguments, then the code might fail unexpectedly. That is why they create a dummy function and inherit from that.

Altri suggerimenti

Regarding use of references to literal object instances it is decoupling the prototype of childCtor from the actual instance of parentCtor's prototype by inserting another function instance.

thefourtheye pretty much answers the question. The first is seen as a little more efficient, but can be made more efficient if only one temporary constructor is created during initialisation, not one on each invocation of 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;
  };
}());

I doubt that the difference is measurable, it just gives you a warm inner glow to save a couple of CPU cycles and bytes of memory from time to time.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top