JavaScript - 函数 bind() 方法
函数 bind() 方法
JavaScript 中的函数 bind() 方法会创建一个具有指定 this 值和可选参数的新函数,而不会立即调用原始函数。它通常用于设置函数的上下文 (this) 并部分应用参数。此方法用于将特定对象绑定到通用函数。
要理解函数 bind() 方法,我们首先应该了解"this"关键字。在 JavaScript(以及其他编程语言中)中,this 是一个特殊关键字,用于在函数中引用调用该函数的对象。 this 的值取决于函数的调用方式,并且 this 的行为在不同上下文中可能有所不同。
语法
JavaScript 函数 bind() 方法的语法如下 -
functionToBind.bind(thisValue, arg1, arg2, ...);
此处的 functionToBind 是要设置其 this 值和参数的原始函数。
参数
thisValue − 调用新函数时,应作为 this 参数传递的值。
arg1, arg2, ... − 调用新函数时将固定(部分应用)的可选参数。这些参数将添加到提供给新函数的参数前面。
现在让我们借助一些程序示例来理解 Function bind() 方法。
不使用 Function bind() 方法
这里我们将创建一个通用的函数 greet(),它只是简单地打印到控制台。我们创建一个名为 person 的常量对象并赋予它一些属性,即 name,然后通过传递消息"Hello"来调用函数 greet。
<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,
在此示例中,当不使用 bind 而直接调用 greet 函数时,this 值未明确设置,导致未定义或全局对象(浏览器环境中的 window)被用作 this。
使用函数 bind() 方法
为了解决上例代码中无法获取任何关联名称的问题,我们使用 bind 函数将对象 person 绑定到函数 greet。
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById("demo");
// 原始函数
function greet(message) {
output.innerHTML = message + ', ' + this.name;
}
// 具有"name"属性的对象
const person = { name: 'John Doe' };
const greetPerson = greet.bind(person, 'Hello');
greetPerson();
</script>
</body>
</html>
输出
Hello, John Doe
bind 方法能够创建一个新的函数 greetPerson,其中 this 值已显式设置为 person 对象,并且参数"Hello"也像前面的代码一样被部分应用。
使用 bind() 可确保函数在所需的上下文中执行,从而避免与 JavaScript 函数中 this 的默认行为相关的问题。
示例:将不同的对象绑定到同一个函数
我们创建了三个具有某个点的 x 和 y 坐标的对象,并创建了一个函数 printVal 来将该点的坐标打印到控制台。bind 方法将这些点绑定到 printVal 函数,并打印每个点的 x 和 y 坐标。
<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
示例:设置函数参数的默认值
这是一个新的场景,我们使用 bind 函数来预定义参数。multiply() 函数只需接受 2 个输入并返回它们的乘积。通过使用 bind() 方法,我们可以根据需要将任何参数设置为默认值。
在下面的示例中,它将变量 y 设置为 2,因此在调用函数时,只需传递一个参数,即 x 为 5,它就会乘以预设的 2,并返回 5x2=10 的输出。
<html>
<body>
<div id = "output"> </div>
<script>
// 带参数的原始函数
function multiply(x, y) {
return x * y;
}
// 使用 bind 预设第一个参数
const multiplyByTwo = multiply.bind(null, 2);
// 仅使用第二个参数调用绑定函数
document.getElementById("output").innerHTML= multiplyByTwo(5);
</script>
</body>
</html>
输出
10
需要注意的是,bind 方法会创建并返回一个新函数,而不会修改原始函数。同一个函数可以重复使用,并且无需实际修改即可适应不同的用例。

