I have a Javascript object that stores a bunch of methods, and also stores some variables. In the normal case when the methods are trying to access each other or the variable it works fine, but if the methods are called from out of scope (say, via another callback) they are no longer able to access the variable.
Example JSFiddle here: http://jsfiddle.net/3Lkuz2Lk/2/
Below is the sample code to illustrate the issue:
var obj = {
x: null,
func1: function() {
console.log('func1, x is ' + this.x);
},
func2: function() {
console.log("func2");
this.func1();
var func1 = this.func1;
func3(function() {
func1();
});
}
};
function func3(callback) {
console.log("func3");
return callback();
}
obj.func2();
The output from the above code is:
func2
func1, x is null
func3
func1, x is undefined
What's not clear to me is why the second time func1 is called x is undefined?
If I need to accomplish this (i.e., be able to access the methods and variables within the object no matter which context they're called from), how can I accomplish that? I find the above approach to be unclean since I need to store the func1 reference in order to be make it available to the call to func3, and I'm hoping there's a cleaner/simpler approach.