简体   繁体   English

何时以及为何使用Call和Apply?

[英]When and why to use Call and Apply?

Firstly I came to know the difference between apply() and call(). 首先,我开始了解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 

From the above code, all the 3 function call displays the alert message. 从上面的代码中,所有3个函数调用都显示警报消息。

  1. What are the advantages/disadvantages of using apply and call, over normal function call, and when is it appropriate to use apply/call, please clarify me. 使用apply和call,优于普通函数调用有什么优点/缺点,什么时候使用apply / call是合适的,请澄清一下。

  2. One more thing, what if the function is a prototype based function: 还有一件事,如果函数是基于原型的函数:

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

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

Then how to call this function bu using apply or call. 然后如何使用apply或call调用此函数。 I tried this way: 我试过这种方式:

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

but resulted in error. 但导致错误。 "ReferenceError: theFunction is not defined" “ReferenceError:未定义函数”

As you have said it seems that you already know what these to functions apply() and call() actually do, but in terms of their uses, I'd say they are used mostly when you want to provide your function with a specific object of your own, as its this value in its context. 正如你所说,似乎你已经知道函数apply()call()实际上做了什么,但就它们的用途而言,我会说它们主要用于你想为function提供特定对象时您自己的,在其上下文中的this值。

One of the most popular use of these two is to handle array-like objects like arguments objects in the function: 这两个中最流行的用法之一是处理类似数组的对象,如arguments中的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);
}

Let's go with another example. 让我们再举一个例子吧。 Say we have an independent function like: 假设我们有一个独立的功能:

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

Now you can use it for any kind of JavaScript object that has a name attribute: 现在,您可以将它用于任何具有name属性的JavaScript对象:

var myInfo = {
    name: 'SAM'
};

now if you do: 现在,如果你这样做:

getName.call(myInfo);

what it does is printing out the name attribute or you can try it on the function itself: 它的作用是打印出name属性,或者你可以在函数本身上尝试:

getName.call(getName);

which would print out the function's name ( "getName" ) in the console. 这将在控制台中打印出函数的名称( "getName" )。

But similar to my first example, it is usually used when you want to use functions that are not in the object's prototype chain. 但与我的第一个例子类似,它通常在你想使用不在对象原型链中的函数时使用。 The other example of that could be: 另一个例子可能是:

//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]"

This post gives a very detailed explanation of call() and apply(). 这篇文章给出了call()和apply()的非常详细的解释。

TLDR; TLDR;

Both call() and apply() are methods we can use to assign the this pointer for the duration of a method invocation call()和apply()都是我们可以用来在方法调用期间分配this指针的方法

The apply() method is identical to call(), except apply() requires an array as the second parameter. apply()方法与call()相同,但apply()需要一个数组作为第二个参数。 The array represents the arguments for the target method. 该数组表示目标方法的参数。

The main difference is that apply lets you invoke the function with arguments as an array; 主要区别在于apply允许您使用参数作为数组调用函数; call requires the parameters be listed explicitly. call需要显式列出参数。

It Will Give You More Explaination POST 它会给你更多解释POST

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM