bind()在JavaScript中的用途是什么?
当前回答
除上述内容外,bind()方法还允许对象从另一个对象借用方法,而无需复制该方法。这在JavaScript中称为函数借用。
其他回答
从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()创建一个新函数,即它返回给您的函数的新引用。
在该关键字后面的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'));
另一种用法是,可以将绑定函数作为参数传递给在另一个执行上下文下运行的另一个函数。
var name = "sample";
function sample(){
console.log(this.name);
}
var cb = sample.bind(this);
function somefunction(cb){
//other code
cb();
}
somefunction.call({}, cb);
我将从理论上和实践上解释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;
考虑下面列出的简单程序,
//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);
推荐文章
- jQuery等价于JavaScript的addEventListener方法
- jQuery需要避免的陷阱
- JavaScript中变量字符串的XML解析
- 'React'指的是一个UMD全局,但当前文件是一个模块
- 为什么useState不触发重新渲染?
- 如何使用回调与useState挂钩在反应
- 网络请求失败
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- 如何使用箭头函数(公共类字段)作为类方法?
- 使用Javascript的atob解码base64不能正确解码utf-8字符串
- 如何阻止恶意代码欺骗“Origin”报头来利用CORS?
- Angular JS:当我们已经有了具有作用域的指令控制器时,指令的link函数还需要什么?
- 我如何在JavaScript中转换对象数组为一个对象?
- 如何让一个按钮将我的页面重定向到另一个页面?
- 如何让元素被点击(对于整个文档)?