Skip to content

Instantly share code, notes, and snippets.

@quangnd
Last active July 19, 2016 10:43
Show Gist options
  • Save quangnd/95ad8ccb5aee4ca327f330f64b1e78b0 to your computer and use it in GitHub Desktop.
Save quangnd/95ad8ccb5aee4ca327f330f64b1e78b0 to your computer and use it in GitHub Desktop.
Explaining Prototype of function as well as Prototype of Object
'use strict';
function Cat(name, color) {
this.name = name
this.color = color
//An empty object is created. After this, JS updates the function's PROTOTYPE property to point to this object (Cat object)
}
Cat.prototype.age = 5; //We haven't even created a Cat object, but PROTOTYPE property created behind the scenes..., then we add the age to the Cat's protype.
var fluffy = new Cat("Fluffy","WHITE") //create new Fluffy object and JS added a __proto__ property to this. And that property is a pointer to Cat function's prototype
var muffin = new Cat("Muffin", "BLUE") //the same processed follow (notice that at this point, muffin (and fluffy) itself doesn't have an age property, only its prototype does.
console.log(fluffy.age); //Result: 5 - this cmd find "age" property of fluffy Object, if not found, it will check its prototype parent to see if it has an age property
fluffy.age = 10; //because fluffy do not have age property, that add age property to fluffy object
console.log(fluffy.age); //get new "age" property - Result: 10
console.log(muffin.age); //get age prototype from Cat function - Result: 5
Cat.prototype = {age: 2} //this command will create a new instance of Cat, and has age property = 2
console.log(fluffy.age); //still 10 because fluffy still refers to first Cat
console.log(muffin.age); //still 10 because muffin still refers to first Cat
var snowbell = new Cat("SnowBell", "YELLOW")
console.log(snowbell.age) //Result: 2 - because snowbell refers to second Cat
//DEFINATIONs:
//1. A funtion's prototype: is the object INSTANCE that will become the prototype for all objects creatd using this fucntion as a constructor.
//2. An object's prototype: is the object INSTANCE from which object is inferited.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment