Last active
April 5, 2017 17:38
-
-
Save roccomuso/4ef203b9985cd2dba43e to your computer and use it in GitHub Desktop.
Prototypal Pattern vs Classical OOP in JS.js
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
var human = { | |
species: "human", | |
create: function(values) { | |
var instance = Object.create(this); | |
Object.keys(values).forEach(function(key) { | |
instance[key] = values[key]; | |
}); | |
return instance; | |
}, | |
saySpecies: function() { | |
console.log(this.species); | |
}, | |
sayName: function() { | |
console.log(this.name); | |
} | |
}; | |
// Musician extends Human, so it inherits all the methods and properties | |
var musician = human.create({ | |
species: "musician", | |
playInstrument: function() { | |
console.log("plays " + this.instrument); | |
} | |
}); | |
// Let's create John | |
var john = musician.create({ | |
name: "John", | |
instrument: "drums" | |
}); | |
john.playInstrument(); // plays drums | |
john.sayName(); // john |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment