Why is it beneficial to rely on the scope chain alone and avoid explicitly referencing the head object in Javascript?

≯℡__Kan透↙ 提交于 2019-12-06 05:16:48

问题


I've been reading this book "Javascript Enlightenment" by Cody Lindley. On page 82 he states: "Being explicit (e.g. window.alert() v.s. alert()) costs a little bit more with regards to performance. It's faster if you rely on the scope chain alone and avoid explicitly referencing the head object even if you know the property you want is contained in the global scope."

I am kind of curious why this is. I would think that it would be the opposite, because the Javascript interpreter could just skip checking the scope and find it directly. I just don't see how it is beneficial to not specify the exact address of something.

I mean, I know I am not going to want to type window.whatever() every time I want to use something contained in the global scope and I think it is great that it is faster to not specify. Just not sure why.

Just one of those "want to know" things.


回答1:


The interpreter always has to use the scope chain. When you write window.alert() it has to walk its way up the scope chain to find the value of window -- you might have a local variable named window that shadows the one in the head, so it can't assume this is the global object.

If JavaScript had a syntax to explicitly denote the top-level context, that would be faster. But it doesn't.



来源:https://stackoverflow.com/questions/13022647/why-is-it-beneficial-to-rely-on-the-scope-chain-alone-and-avoid-explicitly-refer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!