Javascript jquery - 使用 .call() 时传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6016295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:53:59  来源:igfitidea点击:

jquery - pass parameters when using .call()

javascriptjquery

提问by Drew

How can you pass parameters to a function when using .call()in Javascript?

.call()在 Javascript 中使用时如何将参数传递给函数?

When I pass parameters they are always undefined in the callback function

当我传递参数时,它们在回调函数中始终未定义

EDIT (an example):

编辑(一个例子):

I will have an options object in my plugin:

我的插件中有一个选项对象:

var options = {

errorCallback : function( errors ) {}

}

I will call this from my plugin like this:

我将从我的插件中调用它,如下所示:

var errors = "Test error list";
configs.errorCallback.call(errors);

I will initialise my plugin like this

我会像这样初始化我的插件

 $('#plugin-element').myPlugin(
       { 
           'errorCallback' : function errorrCallbackFunction( errors ) {
                   console.log(errors) //always undefined
               }
       }

回答by mck89

The first argument of call is the 'this' of the function. If you want to pass the variable as argument start from the second one.

call 的第一个参数是函数的“this”。如果要将变量作为参数传递,则从第二个开始。

configs.errorCallback.call(undefined, errors);

Here is the documentation: Function.prototype.call()

这是文档: Function.prototype.call()

回答by lonesomeday

configs.errorCallback.call(errors);

This isn't necessary. You only need to use callif you want to set the contextof the function call. That means the value of thiswithin the callback.

这是没有必要的。call如果要设置函数调用的上下文,则只需要使用。这意味着this回调中的值。

If you don't want to set this, then you can just call the function as you normally would:

如果您不想设置this,则可以像往常一样调用该函数:

configs.errorCallback(errors);

If you do want to set this, then you need to set it as the first parameter to call. Subsequent parameters are passed on to the function.

如果确实要设置this,则需要将其设置为 的第一个参数call。随后的参数被传递给函数。

For example:

例如:

var configs = {
    errorCallback : function( errors ) {}
};
configs.errorCallback.call(configs, errors);

Within errorCallback, you can access configsusing the keyword this.

在其中errorCallback,您可以configs使用关键字访问this