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,因为我们在绑定时传递了这些值。
其他回答
绑定允许-
将“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()方法创建一个新函数,当调用该函数时,将其this关键字设置为所提供的值,并在调用新函数时提供的任何参数之前设置一个给定的参数序列。
第一部分的示例
使用St8从反应包中抓取
import { useState } from "react"
function st8() {
switch(arguments.length) {
case 0: return this[0]
case 1: return void this[1](arguments[0])
default: throw new Error("Expected 0 or 1 arguments")
}
}
function useSt8(initial) {
// this in st8 will be something like [state, setSatate]
return st8.bind(useState(initial))
}
// usage
function Counter() {
const count = useSt8(0);
return (
<>
Count: {count()}
<button onClick={() => count(0)}>Reset</button>
<button onClick={() => count(prevCount => prevCount + 1)}>inc</button>
</>
);
}
第二部分的示例
const add = (a, b) => a+b
someThis = this
// new function with this value equal to someThis
add5 = add.bind(someThis, 5)
add5(10) // 15
// we don't use this in add decelartion so this will work too.
add10 = add.bind(null, 10)
add10(5) // 15
我没有读过上面的代码,但我学到了一些简单的东西,所以我想在这里分享一下bind方法,我们可以将它用作任何普通方法。
<pre> note: do not use arrow function it will show error undefined </pre>
让solarSystem={太阳:“红色”,moon:“白色”,sunmoon:函数(){let dayNight=this.sun+'是太阳的颜色,在白天呈现,'+this.moon+'是月亮的颜色,晚上呈现';返回日夜间;}}让工作=功能(工作,睡眠){console.log(this.sunmoon());//访问solatSystem直到现在都显示错误undefine suncommon,因为我们无法直接访问我们使用的.bind()console.log('我在'+work+'中工作,在'+sleep中睡眠);}let outPut=work.bind(solarSystem);outPut(“日”,“夜”)
我将从理论上和实践上解释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;
变量具有局部和全局作用域。假设我们有两个同名的变量。一个是全局定义的,另一个是在函数闭包内定义的,我们希望得到函数闭包内的变量值。在这种情况下,我们使用这个bind()方法。请参见下面的简单示例:
变量x=9;//这是指浏览器中的全局“窗口”对象var人={x: 81中,getX:函数(){返回此.x;}};var y=person.getX;//它将返回9,因为它将调用x的全局值(varx=9)。var x2=y.bind(人);//它将返回81,因为它将调用在名为person(x=81)的对象中定义的x的局部值。document.getElementById(“demo1”).innerHTML=y();document.getElementById(“demo2”).innerHTML=x2();<p id=“demo1”>0</p><p id=“demo2”>0</p>
推荐文章
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何禁用文本选择使用jQuery?
- 如何停止事件冒泡复选框点击
- 如何在PHP中截断字符串最接近于一定数量的字符?
- 向对象数组添加属性
- 如何在Redux应用程序中动态加载代码分割的减速器?