I coded a class in JavaScript, and I'm trying to modify one of my public properties inside a private function.
Here is an example of my code:
MyClass = function(callback){
this.tabs = [];
var tabs_callback = function(){};
this.setTabsCallback = function(callback) {
tabs_callback = callback;
}
var _doStuff = function(callback) {
// doing stuff
this.tabs = [1, 2, 3];
console.log("Inside doStuff");
console.log(this.tabs);
tabs_callback();
}
this.doStuff = function() {
_doStuff();
}
}
var myObject = new MyClass();
myObject.setTabsCallback(function () {
console.log("Inside callback");
console.log(myObject.tabs);
});
myObject.doStuff();
And here is what I get in the console:
Inside doStuff
[ 1, 2, 3 ]
Inside callback
[]
Why am I not able to see my modification from the callback function?
Because
_doStuffis defined as a function, it has its ownthiscontext, which is why you cannot access thethis.tabsthat you defined outside of the private function.There are two simple ways to resolve this.
First, you can simply create a private variable which holds a reference to
thisoutside the function:Or, second, you could instead use an arrow function. Arrow functions are a relatively new addition to Javascript. They do not create a separate context with its own
thisreference, so when you use thethisobject it will still refer to the same object as outside the function, so your function will work correctly: