zoukankan      html  css  js  c++  java
  • 变量提升 ( hoisting )

     

    一 概述

    JavaScript引擎在预编译时,会将声明(函数声明、变量声明)自动提升至函数或全局代码的顶部。但是赋值不会提升。

    Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

    It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached:

    二 var声明的变量,在非严格模式、严格模式都会提升

     

    例一 非严格模式

    function hoisting(){
        // 如果变量未提升,会报错 Uncaught ReferenceError: saint is not defined
        console.log(saint);
        var saint = 'Aioria';
        console.log(saint);
    }
    hoisting();

    例二 严格模式

    var saint = 'Orpheus';
    function hoisting(){
        console.log(saint);
        var saint = 'Aioria';
        console.log(saint);
    }
    hoisting();

    例三 函数

    function test(){
        console.log(name,hello,welcome);
        var name = 'Tom';
        var hello = function(){
            console.log('hello~');
        };
        function welcome(){
            console.log('welcome~');
        }
        hello();
        welcome();
    }
    
    test();

    三 let声明的变量,在非严格模式、严格模式都不会提升。

    function hoisting(){
        console.log(saint);
        let saint = 'Aioria';
        console.log(saint);
    }
    hoisting();

  • 相关阅读:
    DB2 for Z/os Statement prepare
    Foreign key (referential) constraints on DB2 LUW v105
    复制Informational constraints on LUW DB2 v105
    DB2 SQL Mixed data in character strings
    DB2 create partitioned table
    MVC中使用EF的技巧集(一)
    Asp.Net MVC 开发技巧(二)
    Linq使用技巧及查询示例(一)
    Asp.Net MVC 开发技巧(一)
    Asp.Net MVC Identity 2.2.1 使用技巧(八)
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/9006683.html
Copyright © 2011-2022 走看看