Created
February 23, 2016 10:03
-
-
Save deepakkj/97321330e3172ff88018 to your computer and use it in GitHub Desktop.
Prototypal Inheritance in Javascript
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
//prototypal inheritance | |
//parent | |
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); | |
} | |
}; | |
//child | |
var musician = human.create({ | |
species: "musician", | |
playInstrument: function() { | |
console.log("plays " + this.instrument); | |
} | |
}); | |
var will = musician.create({ | |
name: "Will", | |
instrument: "drums" | |
}); | |
will.playInstrument(); // plays drums | |
will.sayName(); //will | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment