Here are 5 small scripts that help you truly understand JavaScript core closures and scopes. Before running the console, try to answer what will pop up in each case, and then you can create a test file to check your answer. Are you ready?
1.
The code copy is as follows:
if (!("a" in window)) {
var a = 1;
}
alert(a);
2.
The code copy is as follows:
var a = 1,
b = function a(x) {
x && a(--x);
};
alert(a);
3.
The code copy is as follows:
function a(x) {
return x * 2;
}
var a;
alert(a);
4.
The code copy is as follows:
function b(x, y, a) {
arguments[2] = 10;
alert(a);
}
b(1, 2, 3);
5.
The code copy is as follows:
function a() {
alert(this);
}
a.call(null);
My prediction answers are: undefined, 1, don't know, 10, null
The answer is at the end of this article. Do you dare to leave your guesses before looking at the answer?
Correct answer: 1. undefined 2. 1 3. function a(x){ return x * 2} 4. 10 5. [object window]