Skip to content

Instantly share code, notes, and snippets.

@jdaly13
Last active December 17, 2015 10:09
Show Gist options
  • Save jdaly13/5592521 to your computer and use it in GitHub Desktop.
Save jdaly13/5592521 to your computer and use it in GitHub Desktop.
prototypal inheritance in javascript example - create an initial object in which other objects will inherit from Use the new Object.create for new browsers and polyfill for older ones
//polyfill for Object.create
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}
var developer = {
init: function (array) {
this.languages = array
},
name:"john doe",
person:true,
languages:[],
booze: {
beer:"miller low life",
whiskey: "jameson",
getDrunk: function (howmanydrinks) {
if (typeof howmanydrinks === 'number' && howmanydrinks > 4)
return "your a trooper"
else {
return "your a lightweight"
}
}
}
}
developer.init(['css', 'html 5', 'javascript']) // her we initalize and pass array
var james = Object.create(developer); we create a new object and it's prototype is developer
james.name = "James"; // append the new object
//delete james.name // if you delete the name property it will look to it's prototype which is John Doe
james.name // outputs James
james.booze.getDrunk(3) //outputs you're a lightweight
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment