Thursday, February 28, 2013

Javascript object prototype

Here is an article about “javascript object prototype”
Javascript objects are dynamic so they can be changed after they are created.
function Pet(name, species, hello) //Pet is camel case, it is class name convention 
{
    this.name = name;
    this.species = species;
    this.hello = hello;
}
var rufus = new Pet("Rufus", "cat", "miaow");
//behind the scene, it means 3 steps
//1. Memory is allocated for the new instance, rufus points to that memory
//2. Pet.call(rufus, "Rufus", "cat", "miaow");
//3. rufus.__proto__ = Pet.prototype;
Pet.prototype.sayHello = function()
{
    alert(this.hello);
}
rufus.sayHello();


The method is added to prototype after the object is created. As rufus has the same prototype of Pet,  although rufus does not have sayHello method, javascript falls back to its prototype and find the sayHello method for the Pet prototype.



No comments:

Post a Comment