使用Function.pr原型.apply()和Function.pr原型.call()调用函数有什么区别?

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

函数.apply();vs func.call();

上述两种方法之间是否存在性能差异?何时最好使用呼叫转移应用,反之亦然?


当前回答

这是一个很好的助记符。应用使用数组,始终使用一个或两个参数。使用Call时,必须计算参数的数量。

其他回答

K.Scott Allen对这件事有很好的评论。

基本上,它们在处理函数参数的方式上有所不同。

apply()方法与call()方法相同,只是apply(需要一个数组作为第二个参数。数组表示目标方法的参数。"

So:

// assuming you have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);

Call()采用逗号分隔的参数,例如:

.call(范围,arg1,arg2,arg3)

apply()接受一个参数数组,例如:

.apply(范围,[arg1,arg2,arg3])

下面是一些更多的用法示例:http://blog.i-evaluation.com/2012/08/15/javascript-call-and-apply/

让我补充一点细节。

这两个调用几乎相等:

func.call(context, ...args); // pass an array as list with spread operator

func.apply(context, args);   // is same as using apply

只有一个微小的区别:

排列运算符。。。允许传递可迭代参数作为要调用的列表。apply只接受类似数组的参数。

因此,这些呼叫是相辅相成的。在我们期望可迭代的地方,调用工作,在我们期望类似数组的地方,应用工作。

对于既可迭代又类似于数组的对象,比如真正的数组,我们技术上可以使用它们中的任何一个,但apply可能会更快,因为大多数JavaScript引擎内部对其进行了更好的优化。

我只想在flatline的一篇解释得很好的文章中添加一个简单的例子,这让初学者很容易理解。

func.call(context, args1, args2 );   // pass arguments as "," separated value

func.apply(context, [args1, args2]); // pass arguments as "Array"

我们还使用“Call”和“Apply”方法更改引用,如下面的代码所定义

设Emp1={名称:'X',getEmpDetail:函数(年龄,部门){console.log(`Name:${this.Name}年龄:${Age}部门:${Department}`)}}Emp1.getEmpDetail(23,'交货')//改变“这个”的第一种方法设Emp2={名称:“Y”,getEmpDetail:Emp1.getEmpDetail}Emp2.getEmpDetail(55,“财务”)//使用“Call”和“Apply”更改“this”的第二种方法设Emp3={name:'Emp3_Object',}Emp1.getEmpDetail.call(Emp3,30,'管理员')//这里我们将ref从**Emp1更改为Emp3**对象//现在这将打印“Name=Emp3_Object”,因为它指向Emp3对象Emp1.getEmpDetail.apply(Emp3,[30,'管理员'])

调用、应用和绑定的另一个示例。Call和Apply之间的区别很明显,但Bind的工作原理如下:

Bind返回可以执行的函数的实例第一个参数是“this”第二个参数是逗号分隔的参数列表(如Call)

}

function Person(name) {
    this.name = name; 
}
Person.prototype.getName = function(a,b) { 
     return this.name + " " + a + " " + b; 
}

var reader = new Person('John Smith');

reader.getName = function() {
   // Apply and Call executes the function and returns value

   // Also notice the different ways of extracting 'getName' prototype
   var baseName = Object.getPrototypeOf(this).getName.apply(this,["is a", "boy"]);
   console.log("Apply: " + baseName);

   var baseName = Object.getPrototypeOf(reader).getName.call(this, "is a", "boy"); 
   console.log("Call: " + baseName);

   // Bind returns function which can be invoked
   var baseName = Person.prototype.getName.bind(this, "is a", "boy"); 
   console.log("Bind: " + baseName());
}

reader.getName();
/* Output
Apply: John Smith is a boy
Call: John Smith is a boy
Bind: John Smith is a boy
*/