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

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

问题描述

我感兴趣什么是在JS中使用call()方法的原因。它似乎重复了调用 this这个的常用方法。例如,我有一个使用call()的代码。

  var obj = {
objType:Dog
}

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

f.call(obj,ate,food);

输出结果是狗食食物。但同样的结果,我可以分配函数的对象。

  var obj = {
objType:Dog
}

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

obj.a = f;
obj.a(吃,食);

结果是一样的。但这种方式更易于理解和使用。为什么需要call()?

解决方案

call 想要控制将在被调用函数中使用的范围。您可能希望 this 关键字不是您分配函数的范围,在这种情况下您可以使用 call apply 来调用你自己的作用域的函数。



F.ex,它也允许你调用范围之外的实用程序方法,例如使用private函数时:

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

obj.publicFn();

在上例中, privateFn 不是在 obj 中公开,但它仍然可以构建,就好像它是公共范围的一部分一样(在中使用>同样的方式)。


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

var obj = {
    objType: "Dog"
}

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

f.call(obj, "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");

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

解决方案

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

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

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