函数 bind() 方法
JavaScript function bind() 方法创建一个具有指定 this 值和可选参数的新函数,而无需立即调用原始函数。它通常用于设置函数的上下文 (this) 并部分应用参数。此方法用于将特定对象绑定到公共函数。
要理解函数 bind() 方法,我们应该首先理解 “this” 关键字。在 JavaScript(以及其他编程语言)中,这是一个特殊的关键字,在函数中用于引用调用函数的对象。this 的值取决于函数的调用方式,并且 this 的行为在不同的上下文中可能会有所不同。
语法
JavaScript function bind() 方法的语法如下 -
functionToBind.bind(thisValue, arg1, arg2, ...);
这里 functionToBind 是你想要设置其 this 值和参数的原始函数。
参数
- thisValue − 调用新函数时应作为 this 参数传递的值。
- arg1, arg2, ... − 调用新函数时将修复(部分应用)的可选参数。这些参数将附加到提供给新函数的参数之前。
现在让我们在一些程序示例的帮助下理解函数 bind() 方法。
无函数 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>
输出
在此示例中,当不使用 bind 直接调用 greet 函数时,不会显式设置 this 值,从而导致未定义的或全局对象(浏览器环境中的窗口)被用作 this。
使用函数 bind() 方法
为了克服前面代码中无法获取任何关联名称的问题,我们使用 bind 函数将对象 person 绑定到函数 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>
输出
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: 200,100
Coordinates: 350,400
示例:设置函数参数的默认值
这是一个新场景,其中我们使用 bind 函数来预定义参数。multiply() 函数只接受 2 个输入并返回它们的乘积。通过使用 bind() 方法,我们可以根据需要将任何参数设置为默认值。
在下面的示例中,它将变量 y 设置为 2,因此在仅通过传递 1 个参数(即 x 为 5)调用函数时,它会乘以预设 2 并返回 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>
输出
需要注意的是,bind 方法会创建并返回一个新函数,并且不会修改原始函数。相同的函数可以重复使用,但无需实际修改即可匹配不同的用例。