开发者

function invocation pattern scoping rules in 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 += t开发者_运维知识库ypeof 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 ?


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.


There are two functions being involved here: one is myObject.double and the other is helper. When you call myObject.double() this refers to myObject. So that === myObject. Later, inside that function, you also call helper(), and inside that scope you have this === the global object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜