Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function invocation pattern scoping rules in JavaScript

Tags:

javascript

Here is a working example from "Javascript - The Good Parts".

function add(x, y){ return x + y};

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

myObject.increment(2);
document.writeln(myObject.value); 

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

    var helper = function (  ) {
        that.value = add(that.value, that.value)
    };

    helper(  );    // Invoke helper as a function.
};

myObject.double(  );
document.writeln(myObject.value);    // 4

For function invocation pattern, 'this' object will have global reference. But I cannot fully understand under-the-hood of mentioned workaround:-

var that = this;    // Workaround.

if we do this, aren't we just copying the reference to 'this' to 'that' ? i.e 'that' will hold to global scope same as 'this' ? how does this work internally ?

like image 676
sojin Avatar asked Dec 06 '10 10:12

sojin


1 Answers

It's not the same here, this refers to myObject so you're getting the right value property it has, this would refer to window...which is why you want to keep the reference like it's doing.

You can test it out here, a few alerts inside the helper function show what's happening pretty well.

An alternative would be to .call() or .apply() the function with the right context, so this continues to refer to the myObject instance you want...like this:

myObject.double = function () {
    var helper = function () {
        this.value = add(this.value, this.value)
    };
    helper.call(this);    // Invoke helper as a function.
};

You can test that version here.

like image 75
Nick Craver Avatar answered Nov 14 '22 23:11

Nick Craver