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();

  • 相关阅读:
    深入理解jsonp跨域请求原理
    vue项目性能优化总结
    脱离Office约束,C#结合Mpxj组件完美解析MSProject(.mpp)文件
    将list转换成DataTable
    json时间格式化
    C# DES加密解密
    asp.net mvc ViewBag常用操作
    Jquery ajax与asp.net MVC前后端各种交互
    存储过程实现树形目录外联其他表实现每个节点的统计
    CSS自定义右键菜单
  • 原文地址:https://www.cnblogs.com/sea-breeze/p/9006683.html
Copyright © 2011-2022 走看看