zoukankan      html  css  js  c++  java
  • JS 变量和函数提升 全局变量和局部变量

    • 变量提升

    1.

    var a = 10;
    function test() {
        a = 100;
        console.log(a);
        console.log(this.a);
        var a;
        console.log(a);
    }
    test();//100  10  100

    =>

    var a = 10;//全局
    function test() {
        var a;//变量提升
        a = 100;//局部
        console.log(a);//局部
        console.log(this.a);//this指向全局window
        console.log(a);//局部
    }
    test();//100  10  100

    2.

    var a = 100;
    function test() {
        console.log(a);
        var a = 10;
        console.log(a);
    }
    test();//undefined  10

    =>

    var a = 100;
    function test() {
        var a;//变量提升
        console.log(a);
        a = 10;
        console.log(a);
    }
    test();//undefined  10

    3.

    var a = 100;
    function test() {
        console.log(a);
        a = 10;
        console.log(a);
    }
    test();
    console.log(a);
    //100  10  10

    =>

    var a = 100;
    function test() {
        console.log(a);//全局
        a = 10;//全局
        console.log(a);//全局
    }
    test();
    console.log(a);
    //100  10  10
    •  函数提升
    console.log(f1); // function f1() {}   
    console.log(f2); // undefined  
    function f1() { }//函数声明
    var f2 = function () { }//函数表达式
        (function (num) {
            var testStr = "test" + num;
            console.log(num);
        })(100);
    console.log(testStr);// testStr is not defined
        (function (num) {
            testStr = "test" + num;//不加var,全局变量
            console.log(num);
        })(100);
    console.log(testStr);// test100
  • 相关阅读:
    c# 正则表达式 首字母转大写
    c# WebBrowser获取cookie
    c# 求最小公倍数
    Response.Redirect与Server.Transfer区别-转
    asp 读文件 比较ip
    asp数组的使用
    如何解决#1045
    mysql limit分页查询效率
    Docker 容器管理:rancher
    Docker监控:google/cadvisor
  • 原文地址:https://www.cnblogs.com/chrisghb8812/p/9921616.html
Copyright © 2011-2022 走看看