使用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();
上述两种方法之间是否存在性能差异?何时最好使用呼叫转移应用,反之亦然?
当前回答
我只想在flatline的一篇解释得很好的文章中添加一个简单的例子,这让初学者很容易理解。
func.call(context, args1, args2 ); // pass arguments as "," separated value
func.apply(context, [args1, args2]); // pass arguments as "Array"
我们还使用“Call”和“Apply”方法更改引用,如下面的代码所定义
设Emp1={名称:'X',getEmpDetail:函数(年龄,部门){console.log(`Name:${this.Name}年龄:${Age}部门:${Department}`)}}Emp1.getEmpDetail(23,'交货')//改变“这个”的第一种方法设Emp2={名称:“Y”,getEmpDetail:Emp1.getEmpDetail}Emp2.getEmpDetail(55,“财务”)//使用“Call”和“Apply”更改“this”的第二种方法设Emp3={name:'Emp3_Object',}Emp1.getEmpDetail.call(Emp3,30,'管理员')//这里我们将ref从**Emp1更改为Emp3**对象//现在这将打印“Name=Emp3_Object”,因为它指向Emp3对象Emp1.getEmpDetail.apply(Emp3,[30,'管理员'])
其他回答
不同之处在于,call()分别接受函数参数,而apply()接受数组中的函数参数。
这是一个很好的助记符。应用使用数组,始终使用一个或两个参数。使用Call时,必须计算参数的数量。
有时,一个对象借用另一个对象的函数是有用的,这意味着借用对象只需像执行自己的函数一样执行借出函数。
一个小代码示例:
var friend = {
car: false,
lendCar: function ( canLend ){
this.car = canLend;
}
};
var me = {
car: false,
gotCar: function(){
return this.car === true;
}
};
console.log(me.gotCar()); // false
friend.lendCar.call(me, true);
console.log(me.gotCar()); // true
friend.lendCar.apply(me, [false]);
console.log(me.gotCar()); // false
这些方法对于为对象提供临时功能非常有用。
这些to方法之间的区别在于,如何传递参数。
“A代表数组,C代表逗号”是一个方便的助记符。
调用、应用和绑定的另一个示例。Call和Apply之间的区别很明显,但Bind的工作原理如下:
Bind返回可以执行的函数的实例第一个参数是“this”第二个参数是逗号分隔的参数列表(如Call)
}
function Person(name) {
this.name = name;
}
Person.prototype.getName = function(a,b) {
return this.name + " " + a + " " + b;
}
var reader = new Person('John Smith');
reader.getName = function() {
// Apply and Call executes the function and returns value
// Also notice the different ways of extracting 'getName' prototype
var baseName = Object.getPrototypeOf(this).getName.apply(this,["is a", "boy"]);
console.log("Apply: " + baseName);
var baseName = Object.getPrototypeOf(reader).getName.call(this, "is a", "boy");
console.log("Call: " + baseName);
// Bind returns function which can be invoked
var baseName = Person.prototype.getName.bind(this, "is a", "boy");
console.log("Bind: " + baseName());
}
reader.getName();
/* Output
Apply: John Smith is a boy
Call: John Smith is a boy
Bind: John Smith is a boy
*/