gpt4 book ai didi

javascript - 掌握 Javascript Function.bind()

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:25:56 26 4
gpt4 key购买 nike

function def() {
console.log(this.x)
}

var f = def.bind({ x:777 })
f() // prints 777

bind 创建了一个函数 f,它与 def 相同,只是在 f 中,this 设置为 { x:777 }

是否可以访问绑定(bind)到 f 之外的对象 f?例如,console.log(f.this.x)(但这不起作用)。或者后面的代码不可能看到 f 绑定(bind)到什么对象?

最佳答案

我在这里找到了一些关于 bind 的有用信息: http://dmitrysoshnikov.com/notes/note-1-ecmascript-bound-functions/

ECMAScript 5 中指定的

bind 生成一种轻量级函数(它在某些方面不同于普通函数,如上面的链接所述。基本上它提供了一个用于调用目标函数的包装器,并维护内部属性,其中包括目标函数、绑定(bind) this 和绑定(bind)参数。由于这些是内部属性,因此无法以 OP 询问的方式访问它们(您不能采用任意绑定(bind)函数 f 并执行类似 f.getBoundThis() 的操作。

值得注意的是,bind 在捕获某些状态方面并不是唯一的。闭包也捕获状态。但是,bind(在 ECMAScript 5 中指定)不是闭包,因为闭包捕获变量而 bind 捕获值。

这是一个例子:

(function () {
var x = 2;

function thisSquared() { return this * this; }
f = thisSquared.bind(x);

g = function() { return x * x; } // g is a closure

console.log(f()); // Squares the captured value (2), prints 4
console.log(g()); // Squares x, prints 4

x = 3;
})();

console.log(f()); // Squares the captured value (still 2), prints 4
console.log(g()); // Squares x, prints 9

一些以前的 bind 实现(在 ECMAScript 5 之前用 JavaScript 编写)与闭包没有这种区别。

关于javascript - 掌握 Javascript Function.bind(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15287925/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com