使用Function.pr原型.apply()和Function.pr原型.call()调用函数有什么区别?
var func = function() {
alert('hello!');
};
函数.apply();vs func.call();
上述两种方法之间是否存在性能差异?何时最好使用呼叫转移应用,反之亦然?
使用Function.pr原型.apply()和Function.pr原型.call()调用函数有什么区别?
var func = function() {
alert('hello!');
};
函数.apply();vs func.call();
上述两种方法之间是否存在性能差异?何时最好使用呼叫转移应用,反之亦然?
当前回答
尽管call和apply实现了相同的功能,但我认为至少有一个地方不能使用call,只能使用apply。这是您希望支持继承并希望调用构造函数的时候。
这里有一个函数允许您创建类,它也支持通过扩展其他类来创建类。
function makeClass( properties ) {
var ctor = properties['constructor'] || function(){}
var Super = properties['extends'];
var Class = function () {
// Here 'call' cannot work, only 'apply' can!!!
if(Super)
Super.apply(this,arguments);
ctor.apply(this,arguments);
}
if(Super){
Class.prototype = Object.create( Super.prototype );
Class.prototype.constructor = Class;
}
Object.keys(properties).forEach( function(prop) {
if(prop!=='constructor' && prop!=='extends')
Class.prototype[prop] = properties[prop];
});
return Class;
}
//Usage
var Car = makeClass({
constructor: function(name){
this.name=name;
},
yourName: function() {
return this.name;
}
});
//We have a Car class now
var carInstance=new Car('Fiat');
carInstance.youName();// ReturnsFiat
var SuperCar = makeClass({
constructor: function(ignore,power){
this.power=power;
},
extends:Car,
yourPower: function() {
return this.power;
}
});
//We have a SuperCar class now, which is subclass of Car
var superCar=new SuperCar('BMW xy',2.6);
superCar.yourName();//Returns BMW xy
superCar.yourPower();// Returns 2.6
其他回答
K.Scott Allen对这件事有很好的评论。
基本上,它们在处理函数参数的方式上有所不同。
apply()方法与call()方法相同,只是apply(需要一个数组作为第二个参数。数组表示目标方法的参数。"
So:
// assuming you have f
function f(message) { ... }
f.call(receiver, "test");
f.apply(receiver, ["test"]);
这些to方法之间的区别在于,如何传递参数。
“A代表数组,C代表逗号”是一个方便的助记符。
我们可以区分调用和应用方法,如下所示
CALL:单独提供参数的函数。若您知道要传递的参数或并没有要传递的变量,则可以使用call。
APPLY:调用以数组形式提供参数的函数。如果不知道要传递给函数的参数有多少,可以使用apply。
使用applyovercall有一个优点,我们不需要更改参数的数量,只需要更改传递的数组即可。
性能上没有太大差异。但我们可以说,调用比应用更快,因为数组需要在apply方法中求值。
区别在于apply允许您以数组的形式调用带有参数的函数;调用要求显式列出参数。一个有用的助记符是“A代表数组,C代表逗号。”
请参阅MDN的申请和通话文档。
伪语法:
函数.应用(值For This,arrayOfArgs)
函数调用(此值,arg1,arg2,…)
从ES6开始,还可以扩展数组以与调用函数一起使用,您可以在这里看到兼容性。
示例代码:
函数函数(名称、专业){console.log(“我的名字是”+name+“,我是”+profession+“。”);}函数(“John”,“fireman”);函数.应用(未定义,[“Susan”,“学校老师”]);函数调用(未定义,“克劳德”,“数学家”);函数调用(未定义,…[“Matthew”,“物理学家”]);//与排列运算符一起使用
这是一个很好的助记符。应用使用数组,始终使用一个或两个参数。使用Call时,必须计算参数的数量。