Created
February 29, 2016 18:53
-
-
Save ironboy/1f5ba07f99fa2c3cdc89 to your computer and use it in GitHub Desktop.
Object.create patterns - with simple super
This file contains 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
// The supershort version | |
// with no extras (as super, named constructors etc.) | |
// And nice way to handle inheritance is by creating a base object | |
// with an extend method | |
var Base = { | |
extend: function(props){ | |
// A new object with this object as its prototype | |
var t = this, obj = Object.create(t); | |
// Assign properties to the new object | |
Object.assign(obj,props); | |
// Store all overridden methods as function properties | |
Object.keys(t).forEach(function(key){ | |
if(obj[key] === t[key]){return;} | |
if(typeof obj[key] + typeof t[key] != "functionfunction"){return;} | |
obj[key].super = t[key]; | |
}); | |
// Return the new object | |
return obj; | |
}, | |
super: function(){ | |
return arguments.callee.caller.super.apply(this,arguments); | |
} | |
}; | |
// Now we can do things in a clean object oriented way | |
var Organism = Base.extend({ | |
alive: true, | |
greet: function greet(){ | |
return "Hi I am " + (this.alive ? "alive" : "dead"); | |
} | |
}); | |
var Animal = Organism.extend({ | |
canMove: true, | |
greet:function(){ | |
return this.super() + ' and I ' + (this.canMove ? "can move" : "can't move"); | |
} | |
}); | |
var Dog = Animal.extend({ | |
name: "Fido", | |
barks: true, | |
greet: function(){ | |
return this.super() + ' and I ' + (this.barks ? "bark" : "don't bark"); | |
} | |
}); | |
var aDog = Dog.extend({name:"Puppe"}); | |
var aDeadDog = Dog.extend({name:"Muppe",barks:false,canMove:false,alive:false}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment