JavaScript中的Function.bind与Closure:如何选择? [英] Function.bind vs Closure in Javascript : how to choose?

查看:55
本文介绍了JavaScript中的Function.bind与Closure:如何选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如此处所述:

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

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

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.

但是它并没有真正说明如何区分这两种情况.我实际上不理解作者避免与范围遍历相关的任何开销"的含义.你能解释一下吗?

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?

推荐答案

在上面的链接的示例中查看此行

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

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

(其中self = this;上面几行).闭包定义的externalFunction方法存在于不同的范围内,这就是为什么它具有与externalObj对象不同的this值的原因.(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)

作用域遍历意味着,当您要获取存在于另一个作用域中的值(变量,对象)时,因此会增加额外的开销(代码执行起来会变慢).

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.

这篇关于JavaScript中的Function.bind与Closure:如何选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆