I wanted to know how can we read the value of a local variable in another class / instance of a class in javascript.
eg:
I have a method in a class :
myClass1.prototype.myMethod0 = function()
{
this._myVar = null; //initialize this._myVar
}
myClass1.prototype.myMethod1 = function(list)
{
this._myVar = msg.list;
}
and
myClass1.prototype.myMethod2 = function()
{
//do something
// and update the list like say:
list1 = this._myVar; //access the this_myVar.
}
and in my another calss say,
myClass2.prototype.myMethod = function()
{
//call the class1's method here..
myClass1.prototype.myMethod2();
}
myMethod2 is a callback and i bind it in myClass2.
It means, actually, myMethod2 is being called like this: myClass1.callback();
But my problem is , when i call myClass1.prototype.myMethod2();, the list1 = this._myVar; is not getting updated and it is becoming undefined. I am not getting the fix for the same.
The problem is the variable, “this._myVar” is “undefined” in myMethod2 of myclass1
What do is possible but not the way you did it:
Without the
varkeyword, a variable is not local but global. So your code actually created a global variablethis_myVarwhich is shared by all JavaScript code on the same page.list1will be undefined ifmyMethod1()was never called.See [here for an introduction into JavaScript OO programming][1].
[EDIT] I see you updated your question and the variable is now accessed via
this. The automatic variablethisis only assigned when the function is called as a “method”.myClass1.prototype.myMethod2()will call the original definition andthiswill be undefined.You have to use code like this:
Inside of
myMethod2, the variablethiswill have the same value asinstif you call it like that.[EDIT2] If you want to access instance properties, then you must call
myMethod2()via an instance ofmyClass1– JavaScript doesn’t try to read your mind what your code might mean.So at the time when you want to call any method of
myClass1, you must have an instance of it. Try to create one inmyClass2:Alternatively, you will have to pass the instance to the method:
But if you call
myMethod2()like any other global method,thiswon’t have any useful value. There is way to say “When I call a function with a prefix ofmyClass1.prototype., then look for an instance ofmyClass1and put that intothis“. What should JavaScript do when there are 15 instances of this type? Select one by random?