Why is it beneficial to rely on the scope chain al

2019-04-09 15:09发布

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条回答
beautiful°
2楼-- · 2019-04-09 15:31

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.

查看更多
登录 后发表回答