zoukankan      html  css  js  c++  java
  • JS 变量提升与函数提升

    变量提升

      在 ES6 出来之前,没有块级作用域,只有全局作用域 和 函数作用域。

      变量提升指的是 将变量声明提升到它所在作用域的最开始部分。

      

      例子:

      

    console.log(foo); // undefined
    var foo = '变量提升';
    console.log(foo)  // 变量提升

      相当于:

    var foo;
    console.log(foo)  // undefined
    foo = '变量提升';
    console.log(foo); // 变量提升

    函数提升

      函数创建有两种方式,一种是函数声明形式,一种是函数字面量形式,而只有 函数声明形式 才有函数提升。

      例子:

      

    console.log(bar);  // f bar() { console.log(123) }
    console.log(bar()); // undefined
    var bar = 456;
    function bar() {
        console.log(123); // 123
    }
    console.log(bar); // 456
    bar = 789;
    console.log(bar); // 789
    console.log(bar()) // bar is not a function

      相当于:

      

    // 函数提升,函数提升优先级高于变量提升
    var bar = function() {
        console.log(123)
    };
    // 变量提升,变量提升不会覆盖(同名)函数提升,只有变量再次赋值时,才会被覆盖
    var bar;
    console.log(bar);
    console.log(bar());
    // 变量赋值,覆盖同名函数字面量
    bar = 456;
    console.log(bar);
    // 再次赋值
    bar = 789
    console.log(bar);
    console.log(bar())

    优先级

      函数提升优先级高于变量提升,且不会被同名变量声明时覆盖,但是会被变量赋值后覆盖。

      例子:

      

    var getName = function(){
        console.log(2);
    }
    function getName (){
        console.log(1);
    }
    getName();

      相当于:

      

    function getName (){
        console.log(1);
    }
    
    var getName = function(){
        console.log(2);
    }
    
    getName();   // 2

      随笔整理自 https://blog.csdn.net/hualvm/article/details/84395850

      感谢博主分享!

  • 相关阅读:
    字段username没有默认值查询(设计数据库一定要养成好习惯,不是主键最好设置为可以为空)
    计算机中常见的一些概念理解
    Git常用的操作
    docker里面运行jenkins详解
    什么是持续交付
    持续集成概念理解
    Jenkins pipeline概念理解
    linux无法启动httpd服务问题
    linux关闭防火墙
    模板【Binary Indexed Tree树状数组】
  • 原文地址:https://www.cnblogs.com/gaosirs/p/10571658.html
Copyright © 2011-2022 走看看