Created
October 14, 2014 09:23
-
-
Save njif/66e272c5c301e807249c to your computer and use it in GitHub Desktop.
Inherit class
This file contains hidden or 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
| 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