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()创建一个新函数,即它返回给您的函数的新引用。
在该关键字后面的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'));
从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,因为我们在绑定时传递了这些值。
/**
* Bind is a method inherited from Function.prototype same like call and apply
* It basically helps to bind a function to an object's context during initialisation
*
* */
window.myname = "Jineesh";
var foo = function(){
return this.myname;
};
//IE < 8 has issues with this, supported in ecmascript 5
var obj = {
myname : "John",
fn:foo.bind(window)// binds to window object
};
console.log( obj.fn() ); // Returns Jineesh
考虑下面列出的简单程序,
//we create object user
let User = { name: 'Justin' };
//a Hello Function is created to Alert the object User
function Hello() {
alert(this.name);
}
//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();
//we create an instance to refer the this keyword (this.name);
通过将参数绑定到值来创建新函数
bind方法从另一个函数创建一个新函数,其中一个或多个参数绑定到特定值,包括隐式this参数。
局部应用
这是部分应用的示例。通常,我们提供一个函数及其所有参数,这些参数会产生一个值。这就是所谓的函数应用程序。我们正在将函数应用于其参数。
高阶函数(HOF)
部分应用程序是高阶函数(HOF)的一个例子,因为它生成了一个新函数,但参数数量较少。
绑定多个参数
可以使用bind将具有多个参数的函数转换为新函数。
函数乘法(x,y){返回x*y;}让multiplyBy10=multiply.bind(null,10);控制台日志(multiplyBy10(5));
从实例方法转换为静态函数
在最常见的用例中,当使用一个参数调用时,bind方法将创建一个新函数,该函数将此值绑定到特定值。实际上,这将实例方法转换为静态方法。
函数乘数(因子){this.factor=系数;}Multiplier.prototype.multiply=函数(x){返回this.factor*x;}函数ApplyFunction(func,value){返回func(值);}var mul=新乘数(5);//生成垃圾(NaN),因为将“undefined”乘以10console.log(ApplyFunction(多个,10));//产生预期结果:50console.log(ApplyFunction(多乘绑定(多),10));
实现有状态回调
以下示例显示了如何使用this的绑定使对象方法充当回调,从而可以轻松更新对象的状态。
函数ButtonPressedLogger(){此计数=0;this.onPressed=函数(){这个.计数++;console.log(“按下按钮”+this.count+“次数”);}for(let d of document.getElementsByTagName(“button”))d.onclick=this.onPressed.bind(this);}new ButtonPressedLogger();<button>按我</button><button>不按我</button>
推荐文章
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何禁用文本选择使用jQuery?
- 如何停止事件冒泡复选框点击
- 如何在PHP中截断字符串最接近于一定数量的字符?
- 向对象数组添加属性
- 如何在Redux应用程序中动态加载代码分割的减速器?