0

I recently have started reading "JavaScript: good parts" and quoting one of the examples which I couldn't understand. I added a test function to the original example:

var add = function(a,b) {
    return a+b;
};

var myObject = {
    val: 0,
    increment: function(inc) {
        this.val += typeof inc == 'number' ? inc : 1;
    }
};

myObject.increment(12);
myObject.increment();
// till this line, the val is equal to 13

// function invocation
myObject.double = function() {
    var that = this;

    // inner function #1
    var helper = function() {
        that.val = add(that.val, that.val);
    };
    // inner function #2
    var test = function(){
        this.val = add(this.val, this.val);
    };

    helper();   // the val is equal to 26
    // test();  // the val is equal to 13
};

When I use that (var that = this) I am referring to myObject's field, val. Also when I use this in my test function, I am referring to the same field in the same object, but the answer is different. any explanation would be appreciated.

2 Answers 2

1

Try running this code in the browser console:

var obj = {
    val: 0
};

obj.func = function() {
    var that = this;

    console.log(this); // this refers to obj

    var test1 = function() {
        console.log(this);
    };

    test1(); // this refers to the global scope or window

    var test2 = function() {
        console.log(that);
    }

    test2(); // this or that refers to obj
}

obj.func();

In javascript, the keyword this can be pretty tricky. The value of this depends on how the function is invoked. The first console.log shows that this within obj.func refers to obj. For the next example, the keyword this is in the scope of the function test1. More importantly, test1 is called differently than obj.func. Because test1 is invoked without a dot to the left (as a property of an object), the keyword this actually refers to the global scope. You can think of the code running like window.test1(). The last example shows why the line var that = this is useful, it maintains the context to obj.

Sign up to request clarification or add additional context in comments.

Comments

1

When you use this in

var test = function(){
   this.val = add(this.val, this.val);
};

this actually refers to test, not myObject, hence this.val is undefined and this.val = add(this.val, this.val); actually does nothing. This is why the val value is not changed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.