Created
February 5, 2014 05:50
-
-
Save joujiahe/8818057 to your computer and use it in GitHub Desktop.
JavaScript Inheritance Patterns
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
// Constructor | |
function Animal(name) { | |
this.name = name; | |
} | |
Animal.prototype.say = function() { return 'Hi!' + this.name; }; | |
function Dog(name) { | |
Animal.call(this, name); | |
} | |
Dog.prototype = new Animal(); | |
Dog.prototype.constructor = Dog; | |
var myDog = new Dog('Johnson'); | |
// Prototypal | |
var animal = { | |
name: undefined, | |
say: function() { return 'Hi!' + this.name; }, | |
}; | |
var dog = Object.create(animal); | |
dog.name = 'Johnson'; | |
// Functional | |
function animal(spec) { | |
var that = { | |
name: spec.name, | |
say: function() { return 'Hi!' + this.name; } | |
}; | |
return that; | |
} | |
function dog(spec) { | |
var that = animal(spec); | |
return that; | |
} | |
var myDog = dog({name: 'Johnson'}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment