Skip to content

Instantly share code, notes, and snippets.

@njif
Created October 14, 2014 09:23
Show Gist options
  • Select an option

  • Save njif/66e272c5c301e807249c to your computer and use it in GitHub Desktop.

Select an option

Save njif/66e272c5c301e807249c to your computer and use it in GitHub Desktop.
Inherit class
function InheritClass(Base, Child, Context) {
if (!Base || !Child)
return;
Base.apply(Context, Array.prototype.slice.call(arguments, 3));
var MemberValue;
for (var MemberName in Base.prototype) {
MemberValue = Base.prototype[MemberName];
if (!Child.prototype[MemberName])
Child.prototype[MemberName] = MemberValue;
}
}
// Usage example:
var Base = function(a,b) {
this._a = a;
this._b = b;
};
Base.prototype = {
getA: function() {
return this._a;
},
getB: function() {
return this._b;
}
};
var Child = function(a,b,c) {
InheritClass(Base, Child, this, a, b);
this._c = c;
}
Child.prototype = {
getC: function() {
return this._c;
}
};
var a = new Base(1,2);
var b = new Child(1,2,3);
console.log(a.getA() + ' ' + a.getB());
console.log(b.getA() + ' ' + b.getB() + ' ' + b.getC());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment