gpt4 book ai didi

javascript - Javascript 中的 Function.bind 与 Closure : how to choose?

转载 作者:行者123 更新时间:2023-12-03 03:23:23 25 4
gpt4 key购买 nike

正如这里所说:

http://jqfundamentals.com/book/index.html

Closures can also be used to resolve issues with the this keyword,which is unique to each scope. Thismechanism can be particularly usefulwhen dealing with callbacks, though inthose cases, it is often better to useFunction.bind, which will avoid anyoverhead associated with scopetraversal.

但它并没有真正说明如何区分这两种情况。事实上,我不明白作者所说的“避免与范围遍历相关的任何开销”是什么意思。你能解释一下吗?

最佳答案

它指的是这样的事情

obj.doSomething = function() {
var that = this;
setTimeout(function() {
// this is the window
// that is the obj
that.doSomethingElse();
}, 50);
};

对比

obj.doSomething = function() {
setTimeout((function() {
// this is the obj
this.doSomethingElse();
}).bind(this), 50);
};

Benchmark 。 chrome 没有明显差异。

关于javascript - Javascript 中的 Function.bind 与 Closure : how to choose?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6397096/

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