Skip to content

Instantly share code, notes, and snippets.

@toddmantell
Created January 13, 2017 14:57
Show Gist options
  • Select an option

  • Save toddmantell/e96fae2dc21d385fd826ba684ff0a88e to your computer and use it in GitHub Desktop.

Select an option

Save toddmantell/e96fae2dc21d385fd826ba684ff0a88e to your computer and use it in GitHub Desktop.
Some examples to facilitate better understanding of the JS Prototypal Inheritance System
//JavaScript Objects and Prototypes: Two ways of understanding prototypes
//Constructor function
function Cat(name, color) {
this.name = name;
this.color = color;
//this.age = 7;
}
console.log(Cat.prototype);
Cat.prototype.age = 1;//Adding the age property to the Cat Prototype Object
console.log(Object.getPrototypeOf(Cat));
var catProto = document.createElement('div');
console.log(Cat.prototype);
//output.innerHTML += '<br />' + Cat.prototype; only if you want to output to html in jsbin
var squeaky = new Cat("Squeaky", "Black and Grey");
console.log(squeaky);
console.log(squeaky.age);//squeaky was not created with an age instance property (like name or color), so it references the prototype's age property
console.log(`Squeaky's prototype is ${squeaky.__proto__}`);
console.log(squeaky.hasOwnProperty('age'));
//Another example that more clearly shows how prototypal inheritance is more like delegation than classical inheritance
var o = {
a: 1,
b: 2
};
var x = Object.create(o);
console.log("Outputting second set of examples____________"); //to make things easier to read in the console :)
console.log(x);
console.log(x.a);//we never added the a value to the x object, so it is getting it from the prototype chain (in this case, o)
console.log(x.__proto__); //prints an object: {a:1, b:2}. Which also says that o is just a reference to this object.
console.log(o); //same as previous line because o is just a reference to the {a:1, b:2} object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment