bind()在JavaScript中的用途是什么?
当前回答
简单解释:
bind()创建一个新函数,即它返回给您的函数的新引用。
在该关键字后面的parameter中,传递要预配置的参数。实际上,它不会立即执行,只是准备执行。
您可以根据需要预配置任意多个参数。
理解绑定的简单示例:
function calculate(operation) {
if (operation === 'ADD') {
alert('The Operation is Addition');
} else if (operation === 'SUBTRACT') {
alert('The Operation is Subtraction');
}
}
addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
其他回答
Bind创建一个新函数,该函数将强制函数内部的this作为传递给Bind()的参数。
下面是一个示例,展示了如何使用bind传递具有正确this的成员方法:
var myButton = {
content: 'OK',
click() {
console.log(this.content + ' clicked');
}
};
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
打印结果:
OK clicked
undefined clicked
OK clicked
您还可以在第一个(this)参数之后添加额外的参数,bind将把这些值传递给原始函数。稍后传递给绑定函数的任何其他参数将在绑定参数之后传递:
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
打印结果:
15
查看JavaScript函数绑定以获取更多信息和交互式示例。
更新:ECMAScript 2015增加了对=>函数的支持。=>函数更紧凑,不会从其定义范围更改this指针,因此您可能不需要经常使用bind()。例如,如果您希望第一个示例中Button上的一个函数将单击回调连接到DOM事件,以下都是实现这一点的有效方法:
var myButton = {
... // As above
hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
};
bind函数创建了一个新函数,其函数体和它所调用的函数相同。它是用这个参数调用的。为什么我们使用bind fun?:当每次创建一个新实例时,我们必须使用第一个初始实例,然后使用bind fun。我们不能重写bind fun.暗示它存储类的初始对象。
setInterval(this.animate_to.bind(this), 1000/this.difference);
绑定允许-
将“this”的值设置为特定对象。这变得非常有用,因为有时这不是预期的。重用方法咖喱函数
例如,您有一个扣除每月俱乐部费用的功能
function getMonthlyFee(fee){
var remaining = this.total - fee;
this.total = remaining;
return this.name +' remaining balance:'+remaining;
}
现在,您希望将此功能重新用于其他俱乐部成员。请注意,每个会员的月费会有所不同。
让我们想象一下Rachel的余额是500,每月会员费是90。
var rachel = {name:'Rachel Green', total:500};
现在,创建一个可以反复使用的函数,每月从她的账户中扣除费用
//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320
现在,相同的getMonthlyFee函数可以用于另一个具有不同会费的会员。例如,Ross Geller的余额为250,每月费用为25
var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200
我将从理论上和实践上解释bind
javascript中的bind是一种方法--Function.prototype.bind.bind是一个方法。它是在函数原型上调用的。此方法创建一个函数,其主体与调用该函数的函数相似,但“This”引用传递给绑定方法的第一个参数。其语法为
var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
示例:--
var checkRange = function(value){
if(typeof value !== "number"){
return false;
}
else {
return value >= this.minimum && value <= this.maximum;
}
}
var range = {minimum:10,maximum:20};
var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
var result = boundedFunc(15); //passing value
console.log(result) // will give true;
从Function.pr原型.bind()上的MDN文档中:
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
这是有效的,因为我们将其值绑定到对象Obj。
它真正有趣的地方是,当你不仅为它绑定一个值,而且为它的参数属性绑定一个:
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
我们现在可以这样做:
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
与Obj.log不同,我们不必传递x或y,因为我们在绑定时传递了这些值。
推荐文章
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?