Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why create a temporary constructor when doing Javascript inheritance?

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?

like image 551
Paul Draper Avatar asked Apr 23 '14 08:04

Paul Draper


1 Answers

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.

like image 169
thefourtheye Avatar answered Nov 15 '22 01:11

thefourtheye