JavaScript 'bind' 方法的用途是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2236747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:24:09  来源:igfitidea点击:

What is the use of the JavaScript 'bind' method?

javascriptfunctionbind

提问by Sandeep Kumar

What is the use of bind()in JavaScript?

bind()在 JavaScript 中有什么用?

回答by nkron

Bind creates a new function that will force the thisinside the function to be the parameter passed to bind().

Bind 创建一个新函数,this该函数将强制将函数内部作为传递给 的参数bind()

Here's an example that shows how to use bindto pass a member method around that has the correct this:

这是一个示例,显示如何使用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

Which prints out:

打印出来:

OK clicked
undefined clicked
OK clicked

You can also add extra parameters after the 1st (this) parameter and bindwill pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:

您还可以在第一个 ( 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));

Which prints out:

打印出来:

15

Check out JavaScript Function bindfor more info and interactive examples.

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

Update: ECMAScript 2015 adds support for =>functions. =>functions are more compact and do not change the thispointer from their defining scope, so you may not need to use bind()as often. For example, if you wanted a function on Buttonfrom the first example to hook up the clickcallback to a DOM event, the following are all valid ways of doing that:

更新:ECMAScript 2015 添加了对=>函数的支持。 =>函数更紧凑,并且不会this从其定义范围更改指针,因此您可能不需要bind()经常使用。例如,如果您希望Button第一个示例中的函数将click回调连接到 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());
  }
};

回答by Renganathan M G

The simplest use of bind()is to make a function that, no matter how it is called, is called with a particular thisvalue.

最简单的用途bind()是创建一个函数,无论它如何调用,都使用特定this值调用。

x = 9;
var module = {
    x: 81,
    getX: function () {
        return this.x;
    }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

Please refer this link for more information

请参阅此链接以获取更多信息

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

回答by Jhankar Mahbub

bindallows-

绑定允许-

  • set the value of "this" to an specific object. This becomes very helpful as sometimes thisis not what is intended.
  • reuse methods
  • curry a function
  • 将“this”的值设置为特定对象。这变得非常有用,因为有时不是预期的。
  • 重用方法
  • 咖喱函数

For example, you have a function to deduct monthly club fees

例如,您有一个功能可以扣除每月的俱乐部费用

function getMonthlyFee(fee){
  var remaining = this.total - fee;
  this.total = remaining;
  return this.name +' remaining balance:'+remaining;
}

Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member.

现在您想为不同的俱乐部成员重复使用此功能。请注意,月费会因会员而异。

Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.

假设瑞秋的余额为 500,每月会员费为 90。

var rachel = {name:'Rachel Green', total:500};

Now, create a function that can be used again and again to deduct the fee from her account every month

现在,创建一个可以反复使用的功能,每个月从她的账户中扣除费用

//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320

Now, the same getMonthlyFee function could be used for another member with a different membership fee. For Example, Ross Geller has a 250 balance and a monthly fee of 25

现在,相同的 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

回答by John Slegers

From the MDN docson Function.prototype.bind():

该MDN文档Function.prototype.bind()

The bind()method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

绑定()方法创建一个新的功能,调用它时,具有其将此关键字设置为所提供的值,与前述的当新功能被调用任何设置参数给定的序列。

So, what does that mean?!

那么,这是什么意思?!

Well, let's take a function that looks like this :

好吧,让我们采用一个看起来像这样的函数:

var logProp = function(prop) {
    console.log(this[prop]);
};

Now, let's take an object that looks like this :

现在,让我们看一个看起来像这样的对象:

var Obj = {
    x : 5,
    y : 10
};

We can bind our function to our object like this :

我们可以像这样将我们的函数绑定到我们的对象上:

Obj.log = logProp.bind(Obj);

Now, we can run Obj.loganywhere in our code :

现在,我们可以Obj.log在代码中的任何位置运行:

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10

This works, because we bound the value of thisto our object Obj.

这是有效的,因为我们将 的值绑定this到我们的对象Obj



Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop:

真正有趣的地方在于,您不仅绑定了 的值this,还绑定了它的参数prop

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');

We can now do this :

我们现在可以这样做:

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

Unlike with Obj.log, we do not have to pass xor y, because we passed those values when we did our binding.

与 不同Obj.log,我们不必传递xy,因为我们在进行绑定时传递了这些值。

回答by krati agarwal

Variables has local and global scopes. Let's suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:

变量有局部作用域和全局作用域。假设我们有两个同名的变量。一个是全局定义的,另一个是在函数闭包内定义的,我们想要获取函数闭包内的变量值。在这种情况下,我们使用这个 bind() 方法。请看下面的简单例子:

var x = 9; // this refers to global "window" object here in the browser
var person = {
  x: 81,
  getX: function() {
    return this.x;
  }
};

var y = person.getX; // It will return 9, because it will call global value of x(var x=9).

var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).

document.getElementById("demo1").innerHTML = y();
document.getElementById("demo2").innerHTML = x2();
<p id="demo1">0</p>
<p id="demo2">0</p>

回答by Willem van der Veen

Summary:

概括:

The bind()method takes an object as an first argument and creates a new function. When the function is invoked the value of thisin the function body will be the object which was passed in as an argument in the bind()function.

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

How does thiswork in JS anyway

this无论如何如何在 JS中工作

The value of thisin javascript is dependent always depends on what Object the function is called. The value of this always refers to the object left of the dot from where is the function is called. In case of the global scope this is window(or globalin nodeJS). Only call, applyand bindcan alter the this binding differently. Here is an example to show how the this keyword works:

this在 javascript 中的值总是依赖于函数被调用的对象。this 的值总是指点左边的对象,从哪里调用函数。在全局范围的情况下,这是window(或globalnodeJS)。只有call,applybind可以不同地改变 this 绑定。下面是一个展示 this 关键字如何工作的例子:

let obj = {
  prop1: 1,
  func: function () { console.log(this); } 
}

obj.func();   // obj left of the dot so this refers to obj

const customFunc = obj.func;  // we store the function in the customFunc obj

customFunc();  // now the object left of the dot is window, 
               // customFunc() is shorthand for window.customFunc()
               // Therefore window will be logged

How is bind used?

绑定是如何使用的?

Bind can help in overcoming difficulties with the thiskeyword by having a fixed object where thiswill refer to. For example:

绑定可以帮助克服this关键字的困难,因为它有一个固定的对象 wherethis将引用。例如:

var name = 'globalName';

const obj = {
  name: 'myName',
  sayName: function () { console.log(this.name);}
}

const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred

say(); // now because this function is executed in global scope this will refer to the global var

const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object

boundSay();  // Now this will refer to the name in the obj object: 'myName'

Once the function is bound to a particular thisvalue we can pass it around and even put it on properties on other objects. The value of thiswill remain the same.

一旦函数被绑定到一个特定的this值,我们就可以传递它,甚至把它放在其他对象的属性上。的值this将保持不变。

回答by dinesh_malhotra

I will explain bind theoretically as well as practically

我将从理论上和实践上解释 bind

bind in javascript is a method -- Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the 'this' refers to the first parameter passed to the bind method. Its syntax is

javascript 中的 bind 是一种方法—— Function.prototype.bind 。绑定是一种方法。它在函数原型上调用。此方法创建一个函数,其主体类似于调用它的函数,但“this”指的是传递给 bind 方法的第一个参数。它的语法是

     var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);

Example:--

例子: -

  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;

回答by Otti

The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:

bind() 方法创建一个新的函数实例,其 this 值绑定到传递给 bind() 的值。例如:

   window.color = "red"; 
   var o = { color: "blue" }; 
   function sayColor(){ 
       alert(this.color); 
   } 
   var objectSayColor = sayColor.bind(o); 
   objectSayColor(); //blue 

Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.

在这里,通过调用 bind() 并传入对象 o,从 sayColor() 创建了一个名为 objectSayColor() 的新函数。objectSayColor() 函数具有与 o 等效的 this 值,因此调用该函数,即使作为全局调用,也会导致显示字符串“blue”。

Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT? FOR WEB DEVELOPERS

参考:Nicholas C. Zakas - 专业 JAVASCRIPT?对于网络开发者

回答by cdiggins

Creating a new Function by Binding Arguments to Values

通过将参数绑定到值来创建新函数

The bindmethod creates a new function from another function with one or more arguments bound to specific values, including the implicit thisargument.

bind方法从另一个函数创建一个新函数,其中一个或多个参数绑定到特定值,包括隐式this参数。

Partial Application

部分申请

This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.

这是部分应用的一个例子。通常我们提供一个函数,它的所有参数都会产生一个值。这称为函数应用程序。我们正在将该函数应用于其参数。

A Higher Order Function (HOF)

高阶函数 (HOF)

Partial application is an example of a higher order function(HOF) because it yields a new function with a fewer number of argument.

部分应用程序是高阶函数(HOF) 的一个示例,因为它产生了一个参数较少的新函数。

Binding Multiple Arguments

绑定多个参数

You can use bindto transform functions with multiple arguments into new functions.

您可以使用bind将具有多个参数的函数转换为新函数。

function multiply(x, y) { 
    return x * y; 
}

let multiplyBy10 = multiply.bind(null, 10);
console.log(multiplyBy10(5));

Converting from Instance Method to Static Function

从实例方法转换为静态函数

In the most common use case, when called with one argument the bindmethod will create a new function that has the thisvalue bound to a specific value. In effect this transforms an instance method to a static method.

在最常见的用例中,当使用一个参数调用时,该bind方法将创建一个新函数,该函数的this值绑定到特定值。实际上,这将实例方法转换为静态方法。

function Multiplier(factor) { 
    this.factor = factor;
}

Multiplier.prototype.multiply = function(x) { 
    return this.factor * x; 
}

function ApplyFunction(func, value) {
    return func(value);
}

var mul = new Multiplier(5);

// Produces garbage (NaN) because multiplying "undefined" by 10
console.log(ApplyFunction(mul.multiply, 10));

// Produces expected result: 50
console.log(ApplyFunction(mul.multiply.bind(mul), 10));

Implementing a Stateful CallBack

实现有状态回调

The following example shows how using binding of thiscan enable an object method to act as a callback that can easily update the state of an object.

下面的例子展示了如何使用 binding ofthis可以使对象方法充当可以轻松更新对象状态的回调。

function ButtonPressedLogger()
{
   this.count = 0;
   this.onPressed = function() {
      this.count++;
      console.log("pressed a button " + this.count + " times");
   }
   for (let d of document.getElementsByTagName("button"))
      d.onclick = this.onPressed.bind(this);
}

new ButtonPressedLogger();      
<button>press me</button>
<button>no press me</button>

回答by mtyson

As mentioned, Function.bind()lets you specify the context that the function will execute in (that is, it lets you pass in what object the thiskeyword will resolve to in the body of the function.

如前所述,Function.bind()允许您指定函数将在其中执行的上下文(也就是说,它允许您在this函数主体中传入关键字将解析为的对象。

A couple of analogous toolkit API methods that perform a similar service:

执行类似服务的几个类似的工具包 API 方法:

jQuery.proxy()

jQuery.proxy()

Dojo.hitch()

道场.hitch()