//my class
function myClass()
{
this.pubVar = 'hello public';
var priVar = 'hello private';
}
myClass.staticMethod = function()
{
//how do i access thos variables here
}
I tried alert(this.pubVar) and alert(priVar) with no success. What am I doing wrong?
I'm going to change the question a bit.. I didn't explain it well the first time through.
How do I declare static variables in a class?
I know with java it's simple, you just put static infront of the variable type and presto you've got a static variable. I can't seem to find that option for javascript..
Since you want to use the instance of the object inside of your method, I think that you are not really wanting to create a static method, what you want, is a method that is applicable and accessible by all the instances.
For doing that you can extend the constructor's prototype:
function MyClass() {
this.pubVar = 'hello public';
var priVar = 'hello private';
}
MyClass.prototype.myMethod = function() {
alert(this.pubVar);
}
var instance = new MyClass();
instance.myMethod(); // alerts 'hello public'
When you extend the prototype of a constructor function, all the members that reside on it, will be inherited to the object instances created with the new operator.
So you define this method only once in your constructor function, and it will be accessible in the context of each instance (the this keyword inside the method refers to the object instance).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With