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


当前回答

另一种用法是,可以将绑定函数作为参数传递给在另一个执行上下文下运行的另一个函数。

var name = "sample";
function sample(){
  console.log(this.name);
}
var cb = sample.bind(this);

function somefunction(cb){
  //other code
  cb();
}
somefunction.call({}, cb);

其他回答

摘要:

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 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创建一个新函数,该函数将强制函数内部的this作为传递给Bind()的参数。

下面是一个示例,展示了如何使用bind传递具有正确this的成员方法:

var myButton = {
  content: 'OK',
  click() {
    console.log(this.content + ' clicked');
  }
};

myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton

打印结果:

OK clicked
undefined clicked
OK clicked

您还可以在第一个(this)参数之后添加额外的参数,bind将把这些值传递给原始函数。稍后传递给绑定函数的任何其他参数将在绑定参数之后传递:

// Example showing binding some parameters
var sum = function(a, b) {
  return a + b;
};

var add5 = sum.bind(null, 5);
console.log(add5(10));

打印结果:

15

查看JavaScript函数绑定以获取更多信息和交互式示例。

更新:ECMAScript 2015增加了对=>函数的支持。=>函数更紧凑,不会从其定义范围更改this指针,因此您可能不需要经常使用bind()。例如,如果您希望第一个示例中Button上的一个函数将单击回调连接到DOM事件,以下都是实现这一点的有效方法:

var myButton = {
  ... // As above
  hookEvent(element) {
    // Use bind() to ensure 'this' is the 'this' inside click()
    element.addEventListener('click', this.click.bind(this));
  }
};

Or:

var myButton = {
  ... // As above
  hookEvent(element) {
    // Use a new variable for 'this' since 'this' inside the function
    // will not be the 'this' inside hookEvent()
    var me = this;
    element.addEventListener('click', function() { me.click() });
  }
};    

Or:

var myButton = {
  ... // As above
  hookEvent(element) {
    // => functions do not change 'this', so you can use it directly
    element.addEventListener('click', () => this.click());
  }
};

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

另一种用法是,可以将绑定函数作为参数传递给在另一个执行上下文下运行的另一个函数。

var name = "sample";
function sample(){
  console.log(this.name);
}
var cb = sample.bind(this);

function somefunction(cb){
  //other code
  cb();
}
somefunction.call({}, cb);