Created
July 25, 2015 21:36
-
-
Save ironboy/9c4aee6279a97a9028a8 to your computer and use it in GitHub Desktop.
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
// 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]; | |
} | |
} | |
}; | |
// 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) | |
// A small Base object with a simple 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; | |
} | |
} | |
var Animal = Base.extend({ | |
alive: true, | |
breath: function(){ | |
return "I take a breath"; | |
} | |
}); | |
var Mammal = Animal.extend({ | |
run: function(){ | |
return "I run"; | |
} | |
}); | |
var Human = Mammal.extend({ | |
name: "John Doe", | |
write: function(){ | |
return this.name + " says: I'm trying to write something!" | |
} | |
}); | |
var Kalle = Human.extend({ | |
name: "Kalle" | |
}); | |
var Eva = Human.extend({ | |
name: "Eva" | |
}); | |
console.log(Kalle.write()); | |
console.log(Eva.write()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment