What is the difference in the invocation of 'this' in these examples?

前端 未结 1 1413
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 02:07

I\'m reading Crockford\'s \'JS: The Good Parts\'. He has two examples using this and I don\'t understand why in one instance he uses this and in another he uses

1条回答
  •  花落未央
    2021-01-20 02:44

    When you do obj.f(), this inside the function f will refer to obj.

    In the first example, deentify() is called on a string. In that function, he only needs the object on which the function was called, the string, which is what this inside the deentify() function is going to refer to.

    Why we need that

    The add1 function needs to store a reference to the original add function somehow. add1 cannot use this, because it is not called as add.add1. This is overcome by creating a closure over that, in which he saves the reference to the function you execute curry() on (add() in the example).

    When you call add.curry(), this will refer to the add function. (Because you called curry()on add). Due to the closure inside the curry function, that will keep its value and will still reference the add function when add1() is called.

    If this was used inside the function returned from curry(), it would refer to the window object.

    Function.method('curry', function() {
        var args = arguments, 
          that = this; //reference to add
        return function () {
            //`apply` calls add
            return that.apply(null, args.concat(arguments)); 
        };
    });
    var add1 = add.curry(1);
    document.writeln(add1(6));
    

    Note: It is important to see, that the first return in the first snippet denotes the deentify() function, whereas the first return in the second snippet denotes the return value of the curry() function.

    If you want to understand the arguments/apply() magic that makes curry work as well, just ask in the comment, I'll be happy to elaborate.

    0 讨论(0)
提交回复
热议问题