lilalinux
lilalinux

Reputation: 3031

JS namespace scopes: "this" inside "var" function evaluates to "window"

I have a class with some public methods and some private methods. The public methods are bound to "this" and the private method use "var".

I call the public method "do()" from outside the class, and there "this" evaluates to "MyClass". However, if I further call the private "something()" method, then "this" evaluates to the global namespace "Window";

function MyClass() {
    // private field
    var keys = ["foo", "bar"];

    // public method
    this.method = function(key) {
        alert(key);
    }

    // private method
    var something = function() {
        console.log("something()");
        console.log(this);
        $.each(keys, function(idx, key){
            this.method(key);
        }.bind(this));
    }

    // public method
    this.do = function() {
        console.log("do()");
        console.log(this);
        something();
    }
}

var test = new MyClass();
test.do();

The above code as a fiddle: https://jsfiddle.net/lilalinux/13m242ce/8/

As I understand it, this.do (assigned inside the constructor) is a "privileged" function and as such should be callable from outside the class and be allowed to access private members (which are the vars and the parameters of the constructor).

Upvotes: 0

Views: 46

Answers (1)

smaili
smaili

Reputation: 1235

Since something is not associated directly with MyClass, its this value will not refer to your MyClass instance. What you should do instead is assign a reference to this outside of something, and refer to that variable within your private function.

Something like this:

function MyClass() {
    var self = this; // <-- keep the reference

    // ...

    // private method
    var something = function() {
        console.log("something()");
        console.log(self);
        $.each(keys, function(idx, key){
            self.method(key);
        }.bind(self));
    }

    // ...
}

Upvotes: 1

Related Questions