Home  >  Article  >  Web Front-end  >  5 small examples that can help you understand JavaScript core closures and scope_javascript skills

5 small examples that can help you understand JavaScript core closures and scope_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:34:521041browse

Here are 5 small scripts that will help you truly understand the core of JavaScript – closures and scope. Before running the console, try answering what will pop up in each case. Then you can create a test file to check your answers. Are you ready?

1,

Copy code The code is as follows:

if (!("a" in window)) {
var a = 1;
}
alert(a);

2.
Copy code The code is as follows:

var a = 1,
b = function a(x) {
          x && a(--x);
};
alert(a);

3.
Copy code The code is as follows:

function a(x) {
Return x * 2;
}
var a;
alert(a);

4.
Copy code The code is as follows:

function b(x, y, a) {
arguments[2] = 10;
alert(a);
}
b(1, 2, 3);

5.
Copy code The code is as follows:

function a() {
alert(this);
}
a.call(null);

My predicted answers are: undefined, 1, don’t know, 10, null

The answer is at the end of this article. Before reading the answer, do you dare to leave your guess?

Correct answer: 1. undefined 2. 1 3. function a(x){ return x * 2} 4. 10 5. [object window]

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn