如何在 JavaScript 中应用 bind() 函数?
javascriptobject oriented programmingfront end technology更新于 2025/7/29 14:04:17
bind()
与输出 value 的 apply() 函数不同,Bind() 函数会生成一个能够执行代码的 function。
如果我们观察以下代码,apply() 函数会生成 value 输出,而 bind() 函数会生成 function 输出。
示例
<html>
<body>
<script>
var obj = {num : 10};
var mul = function(i, j, k){
return this.num * i*j*k;
}
var array = [6,3,4];
document.write(mul.bind(obj,array));
document.write("</br>");
document.write(mul.apply(obj,array));
</script>
</body>
</html>
输出
function () { [native code] }
720
一般来说,当我们将参数传递给任何函数时,将显示值输出。这里也是一样,由于函数是作为输出执行的,如果我们尝试将参数传递给该函数,则将执行值输出。
示例
在下面的示例中,输出函数被分配给一个名为"round"的变量,并将参数传递给该变量,以便获得值输出,而不是函数输出。
<html>
<body>
<script>
var obj = {num : 10};
var mul = function(i, j, k){
return this.num * i*j*k;
}
var array = [6,3,4]
var round = mul.bind(obj);
document.write(round(6,3,4));
document.write("</br>");
document.write(mul.apply(obj,array));
</script>
</body>
</html>
输出
720 720
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

