Created
September 23, 2014 22:34
-
-
Save werelax/a6a92ce8fc69ad3f43d6 to your computer and use it in GitHub Desktop.
Really small JavaScript class library
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 extend() { | |
return Array.prototype.reduce.call(arguments, function(acc, el) { | |
for (var k in el) if (el.hasOwnProperty(k)) acc[k] = el[k]; | |
return acc; | |
}); | |
} | |
function klass(parent, props) { | |
var F = (props && props.init) || function() { return parent.apply(this, arguments); }; | |
F.prototype = extend(Object.create(parent.prototype), props); | |
F._super = F.prototype._super = parent; | |
return F; | |
} | |
/* Usage example: | |
var Silly = klass(Object, { | |
init: function(name) { | |
this.name = name; | |
this.greet(); | |
}, | |
greet: function() { | |
console.log("Hi, I'm", this.name); | |
} | |
}); | |
var Polite = klass(Silly, { | |
init: function(name) { | |
Polite._super.call(this, name); | |
console.log("Nice to meet you!"); | |
} | |
}); | |
var Pedant = klass(Polite, { | |
greet: function() { | |
console.log("I'm known by the name of", this.name); | |
} | |
}); | |
var s = new Silly("Sam"); | |
var p = new Polite("Peter"); | |
var q = new Pedant("Mr. McChicken"); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment