Learning JS (2): Graphic scope interview questions

Ask yourself a few more whys every day, and you will always get unexpected results. The growth path of a rookie Xiaobai (copyer)

Episode 2: Graphical Interview Scope Interview Questions

Interview questions:

var message = 'copyer'

function foo() {
    
    
    console.log(message);      // copyer
}

function bar() {
    
    
    var message = 'james'
    foo()
}

bar()

In the interview question above, the answer is yes copyer. Why?

Here is the problem involved 作用域链. Not much nonsense, just draw a picture.

We know earlier that before the code is executed, it will be lexically parsed by the code and added to the global object.

All codes are 调用栈executed in the JS engine, that is执行上下文栈

insert image description here

Before executing the code, lexical analysis will be performed, and then bound in the global object ( GO)

var GlobalObject = {
    
    
    window: GlobalObject,
    message: undefined,
    foo: 0x100,
    bar: 0x200
}

So during the analysis process, three memory addresses will be created in the heap to store three objects.

insert image description here

It is worth noting that here is determined [parent scope]at compile time父级作用域

After the lexical analysis is completed, the code starts to be executed, and then GOthe variables inside are assigned values

var GlobalObject = {
    
    
    window: GlobalObject,
    message: 'copyer',
    foo: 0x100,
    bar: 0x200
}

Then it is executed bar(), call the bar function, and it will also be created here函数执行上下文(FEC)

insert image description here

An object will also be created here Activation Object(AO)to save precompiled variables and functions. If there are function nests, it will be AOin the object.

Then start executing the code,

var ActivationObject = {
    
    
    message: 'james'
}
foo()

Executing fooa function here will also create one in the call stack 函数执行上下文and recreate an AOobject in the heap. I won't draw here. Just look at the finished picture.

insert image description here

The above is the overall flow chart, execute the function 进栈的操作, after executing the function,出栈的操作

Looking back at the interview question now, foothere is no messagesuch variable in the function (that is , there is no message attribute in the object), then continue to search AOaccording to the scope chain scopechain.AOparentScope

And here parentScopeis GO, which was determined at the time of the initial compilation.

So the message in GO iscopyer , now you know why.

Target:

parentScopedirection of understanding

scopechainoverall line of understanding

Guess you like

Origin blog.csdn.net/James_xyf/article/details/121071515
Recommended