Javascript 简明教程

JavaScript - Function bind() Method

Function bind() Method

JavaScript 中的函数 bind() 方法通过指定 this 值和可选参数创建新函数,而无需立即调用原始函数。它通常用于设置函数的上下文 ( this ) 和部分应用参数。此方法用于将特定对象绑定到公共函数。

The function bind() method in JavaScript creates a new function with a specified this value and optional arguments, without invoking the original function immediately. It is commonly used to set the context (this) for a function and partially apply arguments. This method is used to bind a particular object to a common function.

为了理解函数 bind() 方法,我们首先应该理解 “ this ” 关键字。在 JavaScript(以及其他编程语言中),这是一个特殊关键字,在函数中用于引用被调用函数的对象。this 的值取决于函数的调用方式,并且 this 的行为在不同的上下文中可能有所不同。

To understand the function bind() method, we should first understand the "this" keyword. In JavaScript (and other programming languages also), this is a special keyword that is used within functions to refer to the object on which the function is invoked. The value of this is depended on how a function is being called and behaviour of this can vary in different contexts.

Syntax

JavaScript 函数 bind() 方法的语法如下−

The syntax of JavaScript function bind() method is as follows −

functionToBind.bind(thisValue, arg1, arg2, ...);

此处的 functionToBind 是原始函数,你希望设置其 this 值和参数。

Here functionToBind is the original function whose this value and arguments you want to set.

Parameters

  1. thisValue − The value that should be passed as the this parameter when the new function is called.

  2. arg1, arg2, …​ − Optional arguments that will be fixed (partially applied) when the new function is called. These arguments will be prepended to the arguments provided to the new function.

现在让我们在一些程序示例的帮助下理解函数 bind() 方法。

Lets now understand the Function bind() method with the help of some program examples.

Without Function bind() Method

在此,我们将创建一个通用且常见的函数 greet(),它只简单地打印到控制台。我们创建了一个名为 person 的常量对象,并赋予其一些属性,即 name,然后我们通过传递消息 “Hello” 来调用函数 greet。

Here we will create a general and common function greet() which simply prints to the console. We create a constant object named person and give it some property i.e. name and we then invoke the function greet by passing it a message "Hello".

<html>
<body>
   <div id = "demo"> </div>
   <script>
	  const output = document.getElementById("demo");
      function greet(message) {
         output.innerHTML = message + ', ' + this.name;
	  }
      const person = { name: 'John Doe' };
      greet('Hello');
   </script>
</body>
</html>
Hello,

在此示例中,当直接调用 greet 函数而不使用 bind 时,没有明确设置 this 值,从而导致将未定义的对象或全局对象(在浏览器环境中的 window )用作 this

In this example, when the greet function is called directly without using bind, the this value is not explicitly set, leading to an undefined or global object (window in a browser environment) being used as this.

With Function bind() method

为了解决上一个代码中无法获取任何关联名称的问题,我们使用 bind 函数将对象 person 绑定到函数 greet。

To overcome the issue in the previous code where it could not fetch any associated name, we make use of the bind function to bind the object person to the function greet.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      // Original function
      function greet(message) {
         output.innerHTML = message + ', ' + this.name;
      }
      // Object with a 'name' property
      const person = { name: 'John Doe' };
      const greetPerson = greet.bind(person, 'Hello');
      greetPerson();
   </script>
</body>
</html>
Hello, John Doe

bind 方法能够创建一个新函数 greetPerson,其中 this 值已明确设置为 person 对象,参数 “Hello” 也像上一个代码中的那样部分应用了。

The bind method was able to create a new function greetPerson wherein the this value has been explicitly set to the person object and argument "Hello" is partially applied as in the previous code as well.

使用 bind() 确保函数在所需上下文中执行,防止因 JavaScript 函数中 this 的默认行为而引发的问题。

Using bind() ensures that the function is executed in the desired context, preventing issues related to the default behaviour of this in JavaScript functions.

Example: Binding different objects to same function

我们创建了三个具有 x 和 y 点坐标的对象,创建了函数 printVal 以打印点的坐标到控制台。bind 方法将点绑定到 printVal 函数并打印每个点的 x 和 y 坐标。

We have created three objects with x and y coordinates of a point, a function printVal is created to print to the console the coordinates of the point. The bind method binds the points to the printVal function and prints the x, y coordinates of each of the points.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      const points1 = {
         X: 100,
         Y: 100
      }
      const points2 = {
         X: 200,
         Y: 100
      }

      const points3 = {
         X: 350,
         Y: 400
      }
      function printVal() {
         output.innerHTML += "Coordinates: "+this.X + "," + this.Y + "<br>";
      }

      const printFunc2 = printVal.bind(points1);
      printFunc2();

      const printFunc3 = printVal.bind(points2);
      printFunc3();

      const printFunc4 = printVal.bind(points3);
      printFunc4();
   </script>
</body>
</html>
Coordinates: 100,100
Coordinates: 200,100
Coordinates: 350,400

Example: Setting the default values of function parameters

这是一个使用 bind 函数预定义参数的新场景。multiply() 函数只需输入 2 个数据并返回它们的乘积。通过使用 bind() 方法,我们可以根据需要将任何参数设置为默认值。

This is a new scenario wherein we make use of the bind function to predefine the parameter. The multiply() function simply takes 2 inputs and returns their product. By using the bind() method we can set any of the parameters to a default value as needed.

在下例中,它将变量 y 设置为 2,因此在调用函数时仅传递一个参数,即 x 作为 5,它会乘以预设的 2,并返回 5x2=10 的输出。

In the below example, it sets the variable y to 2 and hence upon calling the function by passing just 1 parameter i.e. x as 5 it gets multiplies by the preset 2 and returns the output of 5x2=10.

<html>
<body>
   <div id = "output"> </div>
   <script>
      // Original function with parameters
      function multiply(x, y) {
         return x * y;
      }

      // Using bind to preset the first parameter
      const multiplyByTwo = multiply.bind(null, 2);

      // Calling the bound function with only the second parameter
      document.getElementById("output").innerHTML= multiplyByTwo(5);
   </script>
</body>
</html>
10

重要的是要注意 bind 函数创建并返回一个新函数,而不会修改原始函数。可以重用同个函数,却能使其匹配不同的用例,而实际不会修改它。

It is important to note that the bind method creates and returns a new function and does not modify the original function. The same function can be reused and yet made to match different use cases without actually modifying.