Friday, August 26, 2011

Javascript - How to create a class


function MyClass()

{

this.publicProperty = "This is public";

var privateProperty = "This is private";

}



MyClass.prototype.CommonMethod = function() {

//this works

return this.publicProperty;



//this doesn't work

return this.privateProperty;

//neither this

return privateProperty;

}


Calling the private variables from the prototype methods are not allowed since they are not defined on the scope of the constructor, hence, don't have access to the constructor's private variables.

The beauty of prototype methods is that only a single instance of the method is created and shared by all instantiated objects of that type.

In order to access the private variables on the prototype methods, have this instead on your class:

function MyClass()

{

this.publicProperty = "This is public";

var privateProperty = "This is private";

this.GetPrivateProperty = function () { return privateProperty; };

}


Since the method "GetPrivateProperty" was defined within the scope of the class, then it has access to the private variables. The methods defined within the class have a separate instance on the memory unlike the prototype methods. They are not shared to all instance of that class type.

So, a good programming practice would be to define prototype methods. :)

No comments:

Post a Comment