Skip to content

Instantly share code, notes, and snippets.

@tborychowski
Created October 14, 2014 09:19
Show Gist options
  • Save tborychowski/012f9d6a1856b2432f62 to your computer and use it in GitHub Desktop.
Save tborychowski/012f9d6a1856b2432f62 to your computer and use it in GitHub Desktop.
JS inheritance
if (!Function.prototype.bind) {
Function.prototype.bind = function (context) {
if (typeof this !== 'function') throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
var args = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fn = function () {},
fBound = function () {
return fToBind.apply(this instanceof fn && context ? this : context,
args.concat(Array.prototype.slice.call(arguments)));
};
fn.prototype = this.prototype;
fBound.prototype = new fn();
return fBound;
};
}
Function.prototype.extend = function (parent) {
this.prototype = new parent();
this.prototype._super = new parent();
var self = this;
for (var m in this.prototype._super) {
if (typeof this.prototype._super[m] === 'function')
this.prototype._super[m] = this.prototype._super[m].bind(this);
}
return this;
};
function Animal(v) { this.type = 'animal'; }
Animal.prototype.validate = function () { console.log('is animal: ', this.type === 'animal'); };
function Dog(v) { this.type = 'dog'; }
Dog.extend(Animal);
Dog.prototype.validate = function () {
console.log('is dog: ', this.type === 'dog');
this._super.validate();
};
Dog.prototype.bark = function () { console.log('hau hau'); };
var a = new Animal(true);
a.validate();
var d = new Dog(10);
d.validate();
// console.log(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment