AngryHacker
AngryHacker

Reputation: 61616

Having trouble understanding the dynamics of this vs self vs nothing.

Consider the following chunk of code:

function Bar() {
    var _self = this;

    this.addPin = function (param1) {
        console.log('addPin');
    }

    function endPin(param1) {
        console.log('endPin');
    }

    _self.addPin(1);
    this.addPin(1);
    addPin(1);        // failse

    endPin(2);
    this.endPin(2);   // fails
}

var foo = new Bar();
foo.addPin(1);  // works
foo.endPin(1);  // does not work

From what I understand from playing with this code, the function declaration of endPin effectively makes it a private method to any outside callers. While this.methodHere type of declaration makes it a public method.

What I am not clear on is the usage of this in the class itself. this refer to the instance of the class. Why, in that case, can't I use this.endPin inside the class. Conversely, why do I have to use this.methodHere syntax when referring to addPin (which was declared using this.methodHere syntax).

Finally the difference between this and _self - I've read that _self preserves the original state of the class (or this). How does it do that if it's a reference supposedly pointing to the same memory location? How is this different from _self in this particular example?

Upvotes: 0

Views: 51

Answers (2)

Andrea Magazzini
Andrea Magazzini

Reputation: 35

You can't use the this.endPin because the function is not defined in the class itself but inside a function.

If you write:

function Bar() {
    // do whatever
    this.endPin(2); // now it should work
}

function endPin(param1) {
    console.log('endPin');
}

Upvotes: 1

Keith
Keith

Reputation: 24191

You have asked a lots of questions here, so lets try and break them down.

this refer to the instance of the class. Why, in that case, can't I use this.endPin inside the class.

Because endPin is not part of the class, it a local function inside your constructor.

Conversely, why do I have to use this.methodHere syntax when referring to addPin (which was declared using this.methodHere syntax).

Because addPin is part of the class, basically the reverse of the first question. Doing func() does not automatically call the function of class.

How is this different from _self in this particular example?

In this case it's not, but if you used _self inside your local function, it would capture scope so it's still pointing to this of the class, instead of the functions scope.

Upvotes: 4

Related Questions