何时以及为什么使用Call and Apply
When and why to use Call and Apply?
首先我了解了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个函数调用显示警报消息。
与普通的函数调用相比,使用apply和call的优点/缺点是什么,什么时候适合使用apply/call,请告诉我。
还有一件事,如果函数是基于原型的函数呢:
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
要求显式列出参数。
它会给你更多的解释邮报》
- Selenium WebDriver and JavaScript change
- call()和apply()实际上是用来欺骗方法处理类似数组的对象的
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- using setTimeout() and .call()
- Ajax call and node.js
- Laravel and JQuery URL call
- 使用js-apply-and-call创建一个webtrend函数来消除重复
- what's the difference between 'call/apply' and &
- 何时以及为什么使用Call and Apply