Thursday, August 6, 2009

JavaScript instance methods vs Class methods

Javascript instance methods are those that start with the "this" keyword where as class methods start with the prototype keyword. The difference between the two is that given an object instance methods are created per object whereas class methods are only one per class and not per instance so you will avoid creating duplicate object methods. Examples of the two are as follows;
1. Instance method example
    this.getName = function(){return;}
2. Class method example
    //ObjName is the name of your object
    ObjName.prototype.getName = function(){return;}
There is another method which is a class only method. The only difference with that is that it cannot access instance variables like the class method above but can only access class only variable. Example is as follows;
//this is a class only variable = 'test';
/*Note that to get the class variable you have to drill down to the prototype object and you cannot access instance variables in class only methods. Only difference between this and the previous method as you can see is that it does not include prototype keyword.*/
ObjName.getName = function(){return;}
But one thing to keep in mind is that the fact that the prototype keyword is not sometimes supported by older browsers.