Problems of this, window and scope in js

look at the following code:

function test(){
    console.log(this === window);
    show();
    window.show();
    function show(){
        console.log(this === window, "fn");
    }
}
function show(){
    console.log(this === window, "local");
}
test();

:
true
true "fn"
true "local"

my understanding is:
1 who calls the function where this is located, this represents who
2 when a function and object is not called by an object, the default is window object
3 when using a variable or function, priority is given to variables and functions in the current scope
first question: do I understand correctly?

but (second question, divided into three small questions)
1 when show () is called in the test () function, is the window object called by default?
2 if the above is true, why is the result different from the explicit window call below?
3 do local variables and local functions belong to window objects?

Thank you all


personally think that whether it is global function or local function (put aside those cases that change bind), as long as you do not explicitly specify bind object, in non-strict mode, it will default bind to the global object.

in other words, it is not because window.show = = show that the caller of show is considered to be window, but because show is simply used for simple function calls, so this is bound to the global object.

show in
test is a this in closure,closure pointing to the global object by default ( window or global ). The result of two show calls is the same?


javascript Advanced programming says that this objects are bound at run time based on the execution environment of the function: in a global function, this equals window, and when a function is called as an object, this equals that object. However, anonymous functions are global, so this objects often point to window

however, the view that anonymous function this is global is still controversial. For more information on this scope, please see
[Javascript] to understand the this scope problem and the influence of new operator on this scope

.
Menu