Home >Web Front-end >JS Tutorial >JavaScript—A detailed look at scopes, scope chains, and preparsing

JavaScript—A detailed look at scopes, scope chains, and preparsing

php是最好的语言
php是最好的语言Original
2018-08-03 09:33:351672browse

Variables include: global variables, local variables

##In JAvaScript, variables defined in functions are local variables

Scope: It is the scope of use of variables,

is divided into: local scope and global scope

There is no block-level scope in js ---Variables defined in a pair of brackets. This variable can be used outside the curly brackets.

Scope chain: To use variables, search from the inside out, layer by layer, and you can find it. Directly use
var num=10; //作用域链 级别:0
   var num2=20;
   var str = "abc"
   function f1() {
     var num2=20;
     function f2() {
       var num3=30;
       console.log(num);
     }
     f2();
   }
   f1();

layer-by-layer search. When searching for the 0-level scope, if the variable is still not found, the result is an error

Pre-parsing: It is parsed in the browser Before the code, advance (promote) the declaration of variables and functions to the top of the scope

(1) Promotion of variables

In the following case, the declaration of variables is advanced , but the value of num is not advanced, the result is

undefined

//变量的提升
    console.log(num);
    var num=100;


//提升之后为:
var num;//变量的声明提前
console.log(num);
    var num=100;

(2)

function declaration is advanced, the code can still be executed

//函数的声明被提前了
    f1();
    function f1() {
      console.log("这个函数,执行了");
    }

But for the following situation, the code reports an error

f2();
    var f2=function () {
        console.log("小杨好帅哦");
    }

//声明提前后:
var f2;//为一个变量,undefind
f2();//undefind加括号是不被认可的,所以报错
    var f2=function () { 
        console.log("小杨好帅哦");
    }

If you want not to report an error, the code can be changed to:

var f2;
    f2=function () {
      console.log("小杨好帅哦");
    };
    f2();

Related articles:

Let’s talk about JavaScript scope and scope chain

In-depth analysis of JavaScript scope and scope chain

Related videos:


Fun with javascript three-level linkage examples

The above is the detailed content of JavaScript—A detailed look at scopes, scope chains, and preparsing. For more information, please follow other related articles on the PHP Chinese website!

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