Search code examples
javascriptoopprototypejsprototype-programming

difference between using this and prototype to define methods of a class in JavaScript?


Possible Duplicate:
Javascript - this Vs. prototype
Advantages of using prototype, vs defining methods straight in the constructor?
Prototype or inline, what is the difference?

When creating a class in JavaScript, how is declaring methods inside the object using this different then declaring it by accessing the prototype ? it seems to me to serve the same purpose.

window.onload = function() { 
    tc = new TestClass();
    tc.init(); //logs initting
    tc.reset(); //logs resetting
    tc.doSomething(); //logs doing something
};


var TestClass = function(){

    this.init = function(){
        console.log("initting");
    }

    this.reset = function(){
        console.log("resetting");
    }

    this.destroy = function(){
        console.log("destroying");
    }

}

TestClass.prototype.doSomething = function(){

    console.log("doing something");
}

Solution

  • In most situations you will have the same functional result. But internally it's quite different in that when you attach the functions to this, then every instance of the type gets its own copy of the function. By attaching the functions to prototype, all instances share the same function instances. Using prototype reduces memory usage.