bind()在JavaScript中的用途是什么?


当前回答

我没有读过上面的代码,但我学到了一些简单的东西,所以我想在这里分享一下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(“日”,“夜”)

其他回答

绑定允许-

将“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()方法。请参见下面的简单示例:

变量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>

/**
 * 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>