5

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?

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
  • Both add a useless object on the inheritance chain of instances of *childCtor*. In the first case, that object is an empty function object. In the second, it's a full *parentCtor* instance. So the first can be seen as more efficient (though it creates a new empty function each time, whereas only one is necessary). – RobG Apr 23 '14 at 09:07
  • here is a interesting read - http://bolinfest.com/javascript/inheritance.php – aked May 05 '14 at 20:57

3 Answers3

5

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

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.

Thomas Urban
  • 4,649
  • 26
  • 32
1

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.

RobG
  • 142,382
  • 31
  • 172
  • 209