Skip to content

Instantly share code, notes, and snippets.

@ironboy
Last active August 29, 2015 14:25
Show Gist options
  • Save ironboy/a0ff85b37edc4940b713 to your computer and use it in GitHub Desktop.
Save ironboy/a0ff85b37edc4940b713 to your computer and use it in GitHub Desktop.
// JavaScript has prototypical inheritance
// so there is no real difference in extending
// something or creating a new instance
// (although the new keyword may have tricked you
// into thinking so)
var debug = true;
// A minimal polyfill for Object.assign
// (an ES6 feature)
Object.assign = Object.assign || function(){
for(var i = 1; i < arguments.length; i++){
for(var j in arguments[i]){
arguments[0][j] = arguments[i][j];
}
}
};
// If debug or no native Object.create
// then replace native Object.create with a variant
// that gives us nicer writeouts of "classnames" in the console
var reusableFuncs = {};
Object.create = !debug && Object.create ? Object.create : function (o,name) {
name = name || "Object";
var F;
if(reusableFuncs[name]){
// avoid eval on "classes" already created - speedier
F = reusableFuncs[name];
}
else {
// Eval necessary for nice debugging "classnames"
eval('F = function ' + name + '() {}');
}
F.prototype = o;
reusableFuncs[name] = F;
return new F();
};
// A small Base object with a simple extend method
// (if debug is on and you send a property $ it will
// be used as a "classname")
var Base = {
extend: function(props){
// A new object with this object as its prototype
var obj = Object.create(this,debug && (props.$ || this.$));
// Assign properties to the new object
Object.assign(obj,props);
// $super
for(var i in props){
if(typeof this[i] + typeof obj[i] == "functionfunction"){
obj[i].$super = this[i];
}
}
return obj;
}
};
// Some objects / "classes"
var Animal = Base.extend({
$: 'Animal',
alive: true,
breath: function(){
return "I take a breath";
}
});
var Mammal = Animal.extend({
$: 'Mammal',
run: function(){
return "I run";
}
});
var Human = Mammal.extend({
$: 'Human',
name: "John Doe",
write: function(){
return this.name + " says: I'm trying to write something!";
},
run: function(){
return this.run.$super() + " on two legs.";
}
});
var Kalle = Human.extend({
name: "Kalle"
});
var Eva = Human.extend({
name: "Eva"
});
// Let's check things out
console.log(Kalle);
console.log(Eva);
console.log(Kalle.write());
console.log(Eva.write());
console.log(Kalle.run());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment