Last active
December 16, 2015 02:09
-
-
Save invernizzie/5360735 to your computer and use it in GitHub Desktop.
Inheritance models that provides:
- Use of the new operator.
- Proper prototype chain and public methods attached to the prototype.
- Private methods (through Function.prototype.call or Function.prototype.apply).
- Class._super_ attribute to access base class' prototype (for calling super-methods easily).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var inherit = function (init) { | |
var base, ctor; | |
base = this; | |
ctor = function () { | |
if (typeof init === 'function') { | |
init.apply(this, arguments); | |
} | |
}; | |
ctor.prototype = new base(); | |
ctor._super_ = base.prototype; | |
ctor.inherit = inherit; | |
return ctor; | |
} | |
var Base = (function() { | |
// TODO: Prevent calling without new. | |
var Base = function () {} | |
function private () { | |
console.log(this.foo); | |
} | |
Base.prototype.public = function (name) { | |
console.log("Base's public " + name); | |
private.apply(this); | |
}; | |
Base.prototype.aMethod = function () { | |
console.log("Base method"); | |
} | |
return Base; | |
})(); | |
Base.inherit = inherit; | |
var Child = (function () { | |
var Child = Base.inherit(function (){ | |
this.foo = 'bar'; | |
}); | |
Child.prototype.public = function (name) { | |
console.log("Child's public"); | |
Child._super_.public.call(this, name); | |
}; | |
return Child; | |
})(); | |
var Third = Child.inherit(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Base = (function() { | |
// TODO: Prevent calling without new. | |
var Base = function () {} | |
function private () { | |
console.log(this.foo); | |
} | |
Base.prototype.public = function (name) { | |
console.log("Base's public " + name); | |
private.apply(this); | |
}; | |
return Base; | |
})(); | |
var Child = (function () { | |
var Child; | |
Child = function () { | |
this.foo = 'bar'; | |
}; | |
Child._super_ = Base.prototype; | |
// Here we set the prototype chain straight and enable inheritance. | |
Child.prototype = new Base(); | |
Child.prototype.public = function (name) { | |
console.log("Child's public"); | |
Child._super_.public.call(this, name); | |
}; | |
return Child; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment