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


当前回答

简单的例子

function lol(second, third) {
    console.log(this.first, second, third);
}

lol(); // undefined, undefined, undefined
lol('1'); // undefined, "1", undefined
lol('1', '2'); // undefined, "1", "2"

lol.call({first: '1'}); // "1", undefined, undefined
lol.call({first: '1'}, '2'); // "1", "2", undefined
lol.call({first: '1'}, '2', '3'); // "1", "2", "3"

lol.apply({first: '1'}); // "1", undefined, undefined
lol.apply({first: '1'}, ['2', '3']); // "1", "2", "3"

const newLol = lol.bind({first: '1'}); 
newLol(); // "1", undefined, undefined
newLol('2'); // "1", "2", undefined
newLol('2', '3'); // "1", "2", "3"

const newOmg = lol.bind({first: '1'}, '2');
newOmg(); // "1", "2", undefined
newOmg('3'); // "1", "2", "3"

const newWtf = lol.bind({first: '1'}, '2', '3');
newWtf(); // "1", "2", "3"

其他回答

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

除上述内容外,bind()方法还允许对象从另一个对象借用方法,而无需复制该方法。这在JavaScript中称为函数借用。

摘要:

bind()方法将对象作为第一个参数,并创建一个新函数。当调用函数时,函数体中this的值将是在bind()函数中作为参数传入的对象。

这在JS中是如何工作的

javascript中this的值始终取决于调用函数的对象。此值始终指调用函数的点左侧的对象。对于全局范围,这是窗口(或nodeJS中的全局)。只有调用、应用和绑定才能以不同方式更改此绑定。下面是一个示例,说明this关键字的工作原理:

让obj={prop1:1,func:function(){console.log(this);}}obj.func();//obj位于点的左侧,因此这是指obj常量customFunc=obj.func;//我们将函数存储在customFunc对象中customFunc();//现在点左边的对象是窗口,//customFunc()是window.customFunc(//因此,将记录窗口

如何使用绑定?

Bind可以帮助克服使用此关键字时遇到的困难,方法是在此处指定一个固定的对象。例如:

var name='globalName';常量对象={name:'myName',sayName:function(){console.log(this.name);}}常量say=obj.sayName;//我们只是存储函数,它的值不会被神奇地传递say();//现在,由于此函数在全局范围内执行,因此将引用全局变量const-boundSay=obj.sayName.bind(obj);//现在,this的值被绑定到obj对象bounday();//现在,这将引用obj对象中的名称:“myName”

一旦函数被绑定到特定的这个值,我们就可以传递它,甚至可以将它放到其他对象的财产中。其价值将保持不变。

bind是一个在java脚本原型中可用的函数,因为名称建议bind用于将您的函数调用绑定到上下文,无论您正在处理什么,例如:

var rateOfInterest='4%';var轴库={利率:“10%”,getRateOfInterest:函数(){return this.rateOfInterest;}}axisBank.getRateOfInterest()//“10%”让我们知道AxisBankInterest=axsBank.getRateOfInterest//当您想将函数调用分配给变量时,我们使用此语法knowAxisBankInterest();//默认情况下,您将在此处获得“4%”的输出,该函数称为wrt全局上下文let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank)//因此这里我们需要将函数调用绑定到其本地上下文knowExactAxisBankInterest()//“10%”

bind函数创建了一个新函数,其函数体和它所调用的函数相同。它是用这个参数调用的。为什么我们使用bind fun?:当每次创建一个新实例时,我们必须使用第一个初始实例,然后使用bind fun。我们不能重写bind fun.暗示它存储类的初始对象。

setInterval(this.animate_to.bind(this), 1000/this.difference);