The reason to use JS .call() method?

后端 未结 4 1304
小鲜肉
小鲜肉 2020-11-30 19:33

I\'m interested what\'s the reason to have call() method in JS. It seems it duplicates usual method of calling this.

For example, I have a code with cal

4条回答
  •  粉色の甜心
    2020-11-30 19:55

    call is used when you want to control the scope that will be used in the function called. You might want the this keyword to be something else than the scope you assigned the function to, in those cases you can use call or apply to call the function with your own scope.

    F.ex, it also allows you to call utility methods outside the scope, like when using "private" functions:

    var obj = (function() {
        var privateFn = function() {
            alert(this.id);
        }
        return {
            id: 123,
            publicFn: function() {
                privateFn.call(this);
            }
        };
    }());
    
    obj.publicFn();
    

    In the example above, privateFn is not exposed in obj but it can still be constructed as if it was a part of the public scope (using this in the same way).

提交回复
热议问题