javascript - 对JavaScript中的bind()函数进行一些解释

标签 javascript

我在MSD中看到了源代码

// Define the original function with four parameters.
var displayArgs = function (val1, val2, val3, val4) {
    document.write(val1 + " " + val2 + " " + val3 + " " + val4);
}

var emptyObject = {};

// Create a new function that uses the 12 and "a" parameters
// as the first and second parameters.
var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");

// Call the new function. The "b" and "c" parameters are used
// as the third and fourth parameters.
displayArgs2("b", "c");

// Output: 12 a b c

我无法理解这个源代码是如何工作的。 Bind函数可以自动映射参数吗?这里,它第二次绑定(bind)了两个参数。

最佳答案

第一个参数始终是您要传递的 this 值,其余参数是函数的参数。您可以部分传递这些参数。

这意味着,如果您现在拥有部分参数,并且希望稍后在可用时传递其余参数,则可以通过使用 this 绑定(bind)函数来实现。

HTH。

关于javascript - 对JavaScript中的bind()函数进行一些解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930989/

相关文章:

javascript - 动态创建具有可变深度的 JavaScript 对象

javascript - 元素在动画循环中向上移动

javascript - Chrome 与 JS : Uncaught SyntaxError: Unexpected token )

javascript - 返回多个组件会导致 libART 错误

javascript - 为什么 Math.min([1,2]) 返回 NaN?

javascript - 使用 Angular 指令有条件加载模板

javascript - 表中的 Angular ng-repeat 用数组迭代键

javascript - 如何使用 jQuery 将元素动画化为其自然高度

javascript - 为什么在示例中 "for loop"与 "let"配合良好,而不与 "var"配合使用?

javascript - 我需要使用 JS 在 HTML 的输入字段中打印 abc\