我已经知道apply和call是类似的函数,它们设置this(函数的上下文)。
区别在于我们发送参数的方式(manual vs array)
问题:
但是什么时候应该使用bind()方法呢?
var obj = {
x: 81,
getX: function() {
return this.x;
}
};
alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));
jsbin
当我们想要分配一个具有特定上下文的函数时,应该使用Bind函数。
var demo = {
getValue : function(){
console.log('demo object get value function')
}
setValue : function(){
setTimeout(this.getValue.bind(this),1000)
}
}
在上面的例子中,如果我们调用demo.setValue()函数并传递这个。getValue函数,那么它不会调用demo。setValue函数,因为setTimeout中的this指向窗口对象,所以我们需要将演示对象context传递给this。getValue函数使用bind。这意味着我们只是将demo对象的上下文传递给function,而不是实际调用function。
希望你能理解。
更多信息请参考
Javascript绑定函数详细了解
调用/apply立即执行函数:
func.call(context, arguments);
func.apply(context, [argument1,argument2,..]);
Bind不会立即执行函数,而是返回包装好的apply函数(供以后执行):
function bind(func, context) {
return function() {
return func.apply(context, arguments);
};
}
function. prototype.call()和function. prototype.apply()都使用给定的这个值调用函数,并返回该函数的返回值。
另一方面,function .prototype.bind()使用给定的这个值创建一个新函数,并返回该函数而不执行它。
让我们取一个这样的函数:
var logProp = function(prop) {
console.log(this[prop]);
};
现在,让我们选择一个这样的对象:
var Obj = {
x : 5,
y : 10
};
我们可以像这样将函数绑定到对象上:
Obj.log = logProp.bind(Obj);
现在,我们可以在代码中的任何地方运行Obj.log:
Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
真正有趣的是,你不仅为this绑定了一个值,还为它的参数prop绑定了一个值:
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
我们现在可以这样做:
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
call():——这里我们单独传递函数参数,而不是数组格式
var obj = {name: "Raushan"};
var greeting = function(a,b,c) {
return "Welcome "+ this.name + " to "+ a + " " + b + " in " + c;
};
console.log(greeting.call(obj, "USA", "INDIA", "ASIA"));
apply():——这里我们以数组格式传递函数参数
var obj = {name: "Raushan"};
var cal = function(a,b,c) {
return this.name +" you got " + a+b+c;
};
var arr =[1,2,3]; // array format for function arguments
console.log(cal.apply(obj, arr));
bind (): -
var obj = {name: "Raushan"};
var cal = function(a,b,c) {
return this.name +" you got " + a+b+c;
};
var calc = cal.bind(obj);
console.log(calc(2,3,4));