Skip to content

Instantly share code, notes, and snippets.

@joujiahe
Created February 5, 2014 05:50
Show Gist options
  • Save joujiahe/8818057 to your computer and use it in GitHub Desktop.
Save joujiahe/8818057 to your computer and use it in GitHub Desktop.
JavaScript Inheritance Patterns
// 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