首先,我了解了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个函数调用都显示了警报消息。
Function.prototype.theFunction =函数(名称、专业){ 警报(“我的名字是”+ name +“,我是”+职业+“);}
然后如何调用此函数,并使用apply或call。我试过这样做:
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician"); 但却导致了错误。"ReferenceError: theFunction未定义“
发布于 2014-05-14 09:08:52
正如您已经说过的,您似乎已经知道这些对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]"发布于 2014-05-14 09:12:21
这个帖子非常详细地解释了call()和apply()。
TLDR;
call()和apply()都是我们可以用来在方法调用期间分配这个指针的方法 apply()方法与调用()完全相同,但apply()需要一个数组作为第二个参数。数组表示目标方法的参数。
发布于 2014-05-14 09:14:01
主要区别在于,apply允许以数组的形式调用带有参数的函数;call要求显式列出参数。
它将为您提供更多的解释帖子
https://stackoverflow.com/questions/23649947
复制相似问题