Pages

Sunday, October 23, 2016

JavaScript: inheritsFrom (and superConstructor?)

Object.prototype.inheritsFrom = function(Super) {
  function newPrototype(prototype) {
    function Prototype() {
    }
    Prototype.prototype = prototype;
    return new Prototype();
  }
  this.prototype = newPrototype(Super.prototype);  
  this.prototype.constructor = this;
};

/* THIS IS FUBAR!
Object.prototype.superConstructor = function() {
  this.__proto__.__proto__.constructor.apply(this, arguments);
};
*/

Example: Foo ← Bar

function Foo(bar) { this.foo = function() { return bar; }; }
Foo.prototype.bar = function() { return this.foo(); };
Foo.BAR = function() { return "FOOBAR"; };

function Bar() { Foo.call(this, "BAR"); }
Bar.inheritsFrom(Foo);

function fooBar() {
  console.log("Foo.BAR(): " + Foo.BAR());
  var foo = new Foo("FOO");
  console.log(foo);
  console.log("foo.bar(): " + foo.bar());
  var bar = new Bar();
  console.log(bar);
  console.log("bar.bar(): " + bar.bar());
}
See Also