javascriptclassooppropertiesprivate-functions

Javascript modify public properties from private functions


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?


Solution

  • Because _doStuff is defined as a function, it has its own this context, which is why you cannot access the this.tabs that 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 this outside the function:

    ...
    var that = this;
    var _doStuff = function(callback) {
        // inside _doStuff, use "that" instead of "this"
    ...
    

    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 this reference, so when you use the this object it will still refer to the same object as outside the function, so your function will work correctly:

    ....
    var _doStuff = (callback) => {
        // now _doStuff doesn't create a new "this" object, so you can still access the one from outside
    ...