简体   繁体   English

我什么时候应该使用call()vs直接调用函数?

[英]When should I use call() vs invoking the function directly?

I've got a JavaScript application that uses a lot of callbacks. 我有一个使用大量回调的JavaScript应用程序。 A typical function will take a callback, and wrap it with another callback. 典型的函数将进行回调,并使用另一个回调进行包装。

Namespace.foo = function( arg, their_on_success ) {
    var my_on_success = function( result ) {
        console.log( 'my_on_success() called' );
        if( 'function' === typeof their_on_success ) {
              their_on_success( result );
        }
    }
    something( arg, my_on_success );
};

Given the above example, when should such a setup us the native call() method (passing the result var as the second argument) rather than invoking their_on_success() and passing in the result via function invocation? 鉴于以上示例,何时应该使用本机call()方法(将结果var作为第二个参数传递)而不是调用their_on_success()并通过函数调用传递结果?

call() is used to change the this value of the function: call()用于更改函数的this值:

var obj = {a: 0};
method.call(obj, "parameter");
function method(para) {
    this.a == 0; // true <-- obj is now this
}

The only reason to use call (or apply ) is if you want to set the value of this inside the function. 使用call (或apply )的唯一原因是,如果要在函数内设置this的值。

Well, I guess apply can be useful in other cases as it accepts an array of parameters. 好吧,我认为apply在其他情况下很有用,因为它接受一组参数。

Using a function's call() method allows you to changed the object that's bound to the function as this during the execution of the function - this is also called the context 使用函数的call()方法允许你更改了绑定到该函数的对象this函数的执行过程中-这也被称为上下文

their_on_success.call(myContext, results)

But, if your callback function does not depend on this , it make no difference which way you call it. 但是,如果您的回调函数不依赖this ,那么您调用它的方式没有区别。

A good example is when implementing a function that needs a callback. 一个很好的例子是在实现需要回调的函数时。 When writing OO code, you want to allow the caller to specify the context that a callback will be called. 在编写OO代码时,您希望允许调用者指定将调用回调的上下文。

function validateFormAjax(form, callback, context) {
  // Using jQuery for simplicity
  $.ajax({
    url: '/validateForm.php',
    data: getFormData(form),
    success: function(data) {
      callback.call(context, data);
    }
  });
}

Note that my example could just be implemented by passing the context parameter to the $.ajax call, but that wouldn't show you much about using call 请注意,我的示例可以通过将context参数传递给$.ajax调用来实现,但这对于使用call不会显示太多

Another case for using call() is when you are in an environment where you can't trust the object's own method hasn't been replaced or you know it doesn't actually have the method you want to run on it. 使用call()的另一种情况是,当您处于一个您无法信任该对象的环境中时,您自己的方法尚未被替换,或者您知道它实际上没有您想要在其上运行的方法。 hasOwnProperty is often such a method - there are many places where javascript objects may not have their own hasOwnProperty method so invoking it as hasOwnProperty.call(obj, propertyName) is prudent. hasOwnProperty通常是这样一种方法 - 有很多地方javascript对象可能没有自己的hasOwnProperty方法,所以调用它作为hasOwnProperty.call(obj,propertyName)是谨慎的。

One scenario I often use "call" is splice arguments: 我经常使用“call”的一种情况是拼接参数:

const fn = function() {
    const args = Array.prototype.slice.call(arguments, 0);
    console.log(args);
}

Notice that arguments is an object. 请注意,参数是一个对象。 the args however is an array. 然而args是一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我什么时候应该使用 `publishReplay` 和 `shareReplay`? - When should I use `publishReplay` vs `shareReplay`? React Native:什么时候应该在构造函数与 componentDidMount 中调用 function - React Native: when should you call function in constructor vs componentDidMount 通过挂起的Parens Vs Function.prototype.call调用函数表达式 - Invoking a function expression with hanging Parens Vs Function.prototype.call 使用bind时,有什么方法可以更改对Javascript函数的调用? - Is there any way I should change my call to a Javascript function when I use bind? 在React JS中,何时应该使用商店vs直接操纵视图的状态? - In React JS, when should you use a store vs directly manipulating the view's state? 调用与调用函数 - Calling vs invoking a function Require.js:扩展模块时可以直接使用原型还是应该使用扩展? - Require.js: When extending a module can I use prototype directly or I should use extend as well? 我什么时候应该使用语法“(function(){...})();”? - When should I use the syntax “(function() {…})();”? nodejs:什么时候应该使用`setImmediate(cb)`vs`cb()`? - nodejs: When should I use `setImmediate(cb)` vs `cb()`? 我何时应该使用KnockoutJS组件与模板? - When should I use KnockoutJS Components vs. Templates?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM