Created
June 7, 2014 13:45
-
-
Save Williammer/92b0fe18a95df3fdf70f to your computer and use it in GitHub Desktop.
jsPatterns.klass.js - the ultimate imitation for 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
| var klass = function (Parent, props) { | |
| var Child, F, i; | |
| // 1. | |
| // new constructor | |
| Child = function () { | |
| if (Child.uber && Child.uber.hasOwnProperty("__construct")) { | |
| Child.uber.__construct.apply(this, arguments); | |
| } | |
| if (Child.prototype.hasOwnProperty("__construct")) { | |
| Child.prototype.__construct.apply(this, arguments); | |
| } | |
| }; | |
| // 2. | |
| // inherit | |
| Parent = Parent || Object; | |
| F = function () {}; | |
| F.prototype = Parent.prototype; | |
| Child.prototype = new F(); | |
| Child.uber = Parent.prototype; | |
| Child.prototype.constructor = Child; | |
| // 3. | |
| // add implementation methods | |
| for (i in props) { | |
| if (props.hasOwnProperty(i)) { | |
| Child.prototype[i] = props[i]; | |
| } | |
| } | |
| // return the "class" | |
| return Child; | |
| }; | |
| //test | |
| var Man = klass(null, { | |
| __construct: function (what) { | |
| console.log("Man's constructor"); | |
| this.name = what; | |
| }, | |
| getName: function () { | |
| return this.name; | |
| } | |
| }); | |
| var first = new Man('Adam'); // logs "Man's constructor" | |
| first.getName(); // "Adam" | |
| var SuperMan = klass(Man, { | |
| __construct: function (what) { | |
| console.log("SuperMan's constructor"); | |
| }, | |
| getName: function () { | |
| var name = SuperMan.uber.getName.call(this); | |
| return "I am " + name; | |
| } | |
| }); | |
| var clark = new SuperMan('Clark Kent'); | |
| clark.getName(); // "I am Clark Kent" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment