Question

i have a simple Javascript "class" im testing right now. I noticed that "this" in my private functions do not point to the object itself, instead, its pointing to the global scope (window).

Why?

Info: i want to keep mode private, so i used var mode instead of this.mode. I also want to keep both internal functions private, so user has no access to it. I basically use .prototype to add public functions to myStorage accessing private members with this.

My code:

var myStorage = function(mymode) {
    var mode = mymode;
    function privateFunctionA() {
      // access this.mode to read mymode from constructor but 
      // this is pointing to window
    };

    function privateFunctionB() {
      // access this.mode to read mymode from constructor but 
      // this is pointing to window
    };

    // check for indexeddb, websql and localstorage
    if(mymode == 'A') {
      privateFunctionA();
    } else {
      privateFunctionB();
    }
};
myStorage.prototype.publicFunc = function() {
  console.log(this.mode); // does this work?
}

var data = new myStorage();
Was it helpful?

Solution

this is always function scoped in JavaScript (unless you pass in a context explicitly using call() or apply(). Therefore, in your private functions, this no longer refers to the same this as in the parent scope. An idiomatic way of handling this in JavaScript is to assign this to a self var in the parent scope. E.g.,

var myStorage = function(mymode) {
    var self = this;
    var mode = mymode;
    function privateFunctionA() {
        console.log(self);
    };
    ...
};

Regarding this snippet:

myStorage.prototype.publicFunc = function() {
    console.log(this.mode); // does this work?
}

You will need to assign mode to this back in your constructor (instead of as a var). So, the constructor would now become:

var myStorage = function(mymode) {
    var self = this;
    this.mode = mymode;
    function privateFunctionA() {
        // works
        console.log(self.mode);
    };
    ...
};

And this.mode will also work in your .publicFunc() in this case.

As one more stylistic note, constructor functions in JavaScript usually use proper camel case (i.e., MyStorage).

OTHER TIPS

I dont think you can access the object itself with this when using prototype, because the scope changes and you loose the reference to the primary object itself, so this becomes the window instead.

Check this other question in order to get some more info:

Use of 'prototype' vs. 'this' in JavaScript?

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top