使用 JS .call() 方法的原因? [英] The reason to use JS .call() method?

查看:26
本文介绍了使用 JS .call() 方法的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在 JS 中使用 call() 方法的原因很感兴趣.它似乎重复了调用 this 的常用方法.

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

例如,我有一个带有 call() 的代码.

For example, I have a code with call().

var obj = {
    objType: "Dog"
}

f = function(did_what, what) {
    alert(this.objType + " " + did_what + " " + what);
}

f.call(obj, "ate", "food");

输出是Dog ate food".但是我可以得到相同的结果,我可以将函数分配给对象.

The output is "Dog ate food". But the same result I can get assigning the function to the object.

var obj = {
    objType: "Dog"
}

f = function(did_what, what) {
    alert(this.objType + " " + did_what + " " + what);
}

obj.a = f;
obj.a("ate", "food");

结果是一样的.但是这种方式更容易理解,使用起来也方便.为什么需要 call()?

The result is the same. But this way is more understandable and convenient to use. Why call() is needed?

推荐答案

call 用于控制将在调用的函数中使用的范围.您可能希望 this 关键字不是您分配函数的范围,在这些情况下,您可以使用 callapply使用您自己的作用域调用该函数.

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,它还允许您在范围之外调用实用程序方法,例如使用私有"函数时:

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();

在上面的例子中,privateFn 没有暴露在 obj 中,但它仍然可以被构造为好像它是公共范围的一部分(使用 this 以同样的方式).

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).

这篇关于使用 JS .call() 方法的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆