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

时间:2014-05-14 08:55:48

标签: javascript prototype-programming

首先,我开始了解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. 还有一件事,如果该函数是基于原型的函数:

  3.   

    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:未定义函数"

3 个答案:

答案 0 :(得分:2)

正如你所说,似乎你已经知道这些功能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);
}

现在,您可以将它用于任何具有name属性的JavaScript对象:

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

答案 1 :(得分:1)

这个post给出了call()和apply()的详细解释。

TLDR;

  

call()和apply()都是我们可以用来分配 this 的方法   方法调用持续时间的指针

     

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

答案 2 :(得分:0)

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

它会给你更多的解释 POST