Why is it beneficial to rely only on a chain of scope and avoid explicit reference to the main object in Javascript?

I read this book "Javascript Enlightenment" by Cody Lindley. On page 82, he states: “Being explicit (e.g. window.alert () vs alert ()) costs a bit more in terms of performance. It's faster if you rely only on the scope chain and avoid explicitly referencing the head object , even if you know that the required property is contained in the global scope. "

I am curious why this is so. I would think it would be the other way around, because the Javascript interpreter could just skip checking the scope and find it directly. I just don’t understand how profitable it is not to provide the exact address.

I mean, I know that I don’t want to type window.whatever () every time I want to use something contained in a global scope, and I think it’s great that it’s faster not to specify. I just don’t know why.

Just one of those who want to "know."

+4
source share
1 answer

The interpreter should always use a chain of scope. When you write window.alert() , it must go through the scope chain to find the window value - you may have a local variable called window that obscures the one in the head, so it cannot accept this global object .

If JavaScript had the syntax to explicitly denote a top-level context, that would be faster. But this is not so.

+6
source

Source: https://habr.com/ru/post/1441427/


All Articles