且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

解引用变量的闭包是否有用?

更新时间:2023-11-29 10:26:04

解除引用实际上是一个令人困惑的词。它不是,你只是缓存一些属性/方法在局部变量。它实际上没有区别,无论你做它访问一些属性/方法在随机对象或使用 Array.prototype.slice 多次访问这些深层嵌套的属性时,很有意义

"Dereferencing" is actually a confusing word for that purpose. Its not that, you just cache some property/method in a local variable. It actually makes no difference whether you do it to access some property/method on a random object or do it with Array.prototype.slice. It makes a lot of sense as soon as you access those deeply nested properties more than once.

现代的浏览器做优化访问相当多。所有现代js引擎使用内部查找表来访问属性。但是,你仍然希望缓存这些深层嵌套的东西,因为在旧的引擎中,它将通过所有涉及的对象来解决它。

Tbh, "modern" browsers do optimize the access quite a lot. All modern js engines uses internal look-up tables to accessed properties. However, you still want to cache those deeply nested stuff since in older engines, it would go the whole way down through all involved objects to resolve it.

还有一个原因使用本地缓存引用是,即使现代js引擎不使用哈希查找一旦某种显式或隐式 eval 机制。

One more reason to use local cached references is, that even modern js engines won't use a hash-lookup as soon as some kind of explicit or implicit eval mechanism is used.

特别是Internet Explorer< 9和Firefox 3.5在每个额外的步骤(原型)链中造成了可怕的性能损失。

Especially Internet Explorer <9 and Firefox 3.5 incur a terrible performance penalty with each additional step into a (prototype) chain.

注意:不建议对对象方法使用本地缓存(就像使用 slice 方法)。许多对象使用 this 来确定它们被调用的上下文。在局部变量中存储方法会导致绑定到全局对象 null
因此,一定要使用 method.call 调用这样的方法来手动设置上下文。

One word of caution: it is not very recommended to use local caching for object methods (like you do with the slice method). Many objects use this to determine the context in which they are beeing called. Storing a method in a local variable causes this to be bound to global object or null. So always make sure to call such a method with method.call to set the context manually.