JavaScript Scope (Day 7)

We all know that js code is executed from top to bottom, but let's take a look at the following code;

test();

function test(){

  console.log("hello world");

};

If we simply think that js is executed from top to bottom, then the above code should report an error, indicating that test is not a method; but the result is not an error, but the correct output;

So we should know that js execution is divided into two parts

1. Pre-parse; 2. Execution

Pre-parse will process variables and functions defined by var in advance;

That is, the above code will be processed as

function test(){

  console.log("hello world");

}

test();

So the call does not report an error;

Let's test var again

alert(a);

var a=1;

At this time, the pop-up is undefined; note that there is no error;

The above code is actually pre-parsed as

var a;

alert(a);

a=1;

So what pops up is an undefined;

When the variable has the same name as the function, the promotion of the variable will be ignored. Let's look at an example.

console.log(test);

function test(){

}

console.log(test);

var test = 123;

console.log(test);

The above code will be preprocessed as

function test(){

}

console.log(test);

console.log(test);

test=123;

console.log(test);

We can see that variable name hoisting is ignored;

Function expressions are not hoisted, such as

test();

var test = function () {

};

At this time, it will report an error; it will prompt that test is not a method;

The preprocessed code is

var test;

test();

test=function(){

};

There is no block-level scope in js;

E.g

if(true){

  var a=123;

}

In other languages, such as java, the c# variable a is only valid in the if block-level scope;

But in js there is no such block scope; it will be preprocessed as

var a;

if(true){

  a=123;

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325838376&siteId=291194637