Created
February 29, 2016 18:05
-
-
Save ironboy/2b3189013cf356c80e4c to your computer and use it in GitHub Desktop.
Supershort version of Object.create - extend pattern
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 polyfills or 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 obj = Object.create(this); | |
// Assign properties to the new object | |
Object.assign(obj,props); | |
return obj; | |
} | |
}; | |
// Now we can do things in a clean object oriented way | |
var Organism = Base.extend({ | |
alive: true, | |
greet: function(){ | |
return "Hi I am " + (this.alive ? "alive" : "dead"); | |
} | |
}); | |
var Animal = Organism.extend({ | |
canMove: true, | |
greetOrganism: Organism.greet, | |
greet:function(){ | |
return this.greetOrganism() + ' and I ' + (this.canMove ? "can move" : "can't move"); | |
} | |
}); | |
var Dog = Animal.extend({ | |
name: "Fido", | |
barks: true, | |
greetAnimal: Animal.greet, | |
greet: function(){ | |
return this.greetAnimal() + ' 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