The problem of the scope of js function.

there are some things I don"t understand about the scope of the function, so paste the code first.
function Foo () {

getName = function () { alert (1); }

}
Foo ();
getName (); / / 1

function Foo () {

getName = function () { alert (1); }
return window

}
Foo (). GetName (); / / 1

function Foo () {

getName = function () { alert (1); }

}
Foo (). GetName (); / / error
first of all, all three pieces of code are of the same type, 1. The first thing I understand is that after the global Foo () is executed, a variable getName is created in the global, that is, window, and the function () {alert (1);} is assigned to him. Then call this function globally to get 1.2. The second piece of code is written in succession, and the content can be basically understood, or the variables are created and assigned in the global first. Then a value window is returned. And then it"s the equivalent of window. GetName (). Get 1. 3, the third paragraph of the code I don"t understand, first of all, after the foo execution, you can still create variable assignments in the global. The Foo function then exits the execution environment of the function, and then gives it to the previous execution environment, window. Then call getName, as I understand it. I know that there must be something wrong, not that people will not use return window. What I don"t understand now is why return window, and what has been done in the process of Foo (). GetName ()? After watching it for a long time today, I still don"t quite understand it.

Mar.16,2021

the third code executes Foo () and returns undefined undefined.getName (). Are you sure undefined? popped up?

Menu