Javascript 中的 Function.bind 与 Closure:如何选择?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6397096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:31:45  来源:igfitidea点击:

Function.bind vs Closure in Javascript : how to choose?

javascript

提问by user310291

As said here:

正如这里所说:

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

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

Closures can also be used to resolve issues with the this keyword, which is unique to each scope. This mechanism can be particularly useful when dealing with callbacks, though in those cases, it is often better to use Function.bind, which will avoid any overhead associated with scope traversal.

闭包也可用于解决 this 关键字的问题,该关键字对每个作用域都是唯一的。这种机制在处理回调时特别有用,但在这些情况下,通常最好使用 Function.bind,这将避免与范围遍历相关的任何开销。

But it doesn't really say how to distinguish between the two cases. I don't understand in fact what the author means by "avoid any overhead associated with scope traversal." Can you explain?

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

采纳答案by Pantelis

Take a look at this line in the example in the link above

看看上面链接中示例中的这一行

console.log(self.myName, this.myName);

(with self = this; a couple of lines above). The closure defined outerFunction method, exists in a different scope that is why it has a different this value from the outerObj object. (self.myName!=this.myName)

(self = this;上面几行)。闭包定义的outerFunction 方法存在于不同的作用域中,这就是为什么它与outerObj 对象具有不同的this 值。(self.myName!=this.myName)

Scope traversal means, when you are reaching to grab a value (variable,object) that exists in a different scope, therefore additional overhead is added (code becomes slower to execute).

范围遍历意味着,当您要获取存在于不同范围中的值(变量、对象)时,会增加额外的开销(代码执行速度变慢)。

Using bind, you 're calling a function with an existing scope, so that scope traversal does not take place.

使用绑定,您正在调用具有现有作用域的函数,因此不会发生作用域遍历。

回答by Raynos

What it's referring to are things like this

它所指的是这样的事情

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

vs

对比

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

Benchmark. No noticable difference in chrome.

基准。铬没有明显差异。