何时以及为什么使用Call and Apply

When and why to use Call and Apply?

本文关键字:Call and Apply 为什么 何时      更新时间:2023-09-26

首先我了解了apply()和call()的区别

function theFunction(name, profession) {
    alert("My name is " + name + " and I am a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]); // This call be called theFunction("Susan", "school teacher");, why use apply
theFunction.call(undefined, "Claude", "mathematician"); // This call be called theFunction("Claude", "mathematician");, why use call 

从上面的代码,所有的3个函数调用显示警报消息。

  1. 与普通的函数调用相比,使用apply和call的优点/缺点是什么,什么时候适合使用apply/call,请告诉我。

  2. 还有一件事,如果函数是基于原型的函数呢:

Function.prototype。theFunction = function(name, profession) {

    alert("My name is " + name + " and I am a " + profession + ".");
}

然后如何调用这个函数,除了使用apply或call。我试过了:

theFunction.apply(undefined, ["Susan", "school teacher"]); 
theFunction.call(undefined, "Claude", "mathematician"); 

,但导致错误。ReferenceError: theFunction is not defined"

正如你所说的,你似乎已经知道apply()call()这些函数实际上是做什么的,但就它们的用途而言,我想说它们主要是在你想为你的function提供你自己的特定对象时使用的,作为它在其上下文中的this值。

这两者最常用的用途之一是处理类似数组的对象,如函数中的arguments对象:

function(){
    //let's say you want to remove the first parameter from the arguments object
    //you can make sure that
    console.log(arguments instanceof Array);//false
    //as you see arguments is not an actual array object but it is something similar
    //and you want slice out its value
    var myparams = Array.prototype.slice.call(arguments, 1);
    //here you have myparams without your first argument
    console.log(arguments);
}

让我们看另一个例子。假设我们有一个独立的函数,如:

function getName(){
    console.log(this.name);
}

现在你可以使用它的任何类型的JavaScript对象的name属性:

var myInfo = {
    name: 'SAM'
};

现在如果你这样做:

getName.call(myInfo);

它会打印出name属性或者你可以在函数本身上试试:

getName.call(getName);

将在控制台中打印出函数名("getName")。

但是与我的第一个例子类似,它通常用于当你想使用不在对象原型链中的函数时。另一个例子是:

//let's say you have an array
var myArray = [1 , 2];
//now if you use its toString function
console.log(myArray.toString());//output: "1,2"
//But you can use the Object toString funcion
//which is mostly useful for type checking
console.log(Object.prototype.toString.call(myArray));//output: "[object Array]"

这篇文章非常详细地解释了call()和apply()

TLDR;

call()和apply()都是可以用来赋值的方法。方法调用期间的指针

apply()方法与call()方法相同,除了apply()需要一个数组作为第二个参数。的参数目标方法。

主要区别在于apply允许您以数组的形式使用参数调用函数;call要求显式列出参数。

它会给你更多的解释邮报》