本文介绍了通话和申请有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 call apply 来调用函数有什么区别?

  var func = function(){
alert('hello!');
};

func.apply(); p>

vs

  func.call(); 

这两种方法之间是否存在性能差异?何时最好使用调用超过 apply ,反之亦然?

apply 可以让你使用 arguments 作为一个数组; call 要求显式列出参数。一个有用的助记符是 a rray和 C 用于 c omma的 A



有关和。



伪语法:
$ b $ theFunction.apply(valueForThis,arrayOfArgs)



theFunction.call(valueForThis,arg1,arg2,...)



ES6还有可能 spread 用于调用函数的数组,您可以看到兼容性。



桑普le code:

function theFunction(name,profession){console.log 我的名字是+ name +,我是+职业+。);} theFunction(John,fireman); theFunction.apply(undefined,[Susan,school teacher] ); theFunction.call(undefined,Claude,mathematician); theFunction.call(undefined,... [Matthew,物理学家]); //与扩展运算符一起使用


What is the difference between using call and apply to invoke a function?

var func = function(){
  alert('hello!');
};

func.apply();

vs

func.call();

Are there performance differences between the two methods? When is it best to use call over apply and vice versa?

解决方案

The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."

See MDN's documentation on apply and call.

Pseudo syntax:

theFunction.apply(valueForThis, arrayOfArgs)

theFunction.call(valueForThis, arg1, arg2, ...)

There is also, as of ES6, the possibility to spread the array for use with the call function, you can see the compatibilities here.

Sample code:

function theFunction(name, profession) {
    console.log("My name is " + name + " and I am a " + profession +".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator

这篇关于通话和申请有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 12:49