zoukankan      html  css  js  c++  java
  • 对javascript变量提升跟函数提升的理解

    在写javascript代码的时候,经常会碰到一些奇怪的问题,例如:

    console.log(typeof hello);
    var hello = 123;//变量
    function hello(){//函数声明
    
    }
    console.log(typeof hello);
    var hello = function(){//函数表达式
    }
    console.log(typeof hello);
    //function number function

    对于为什么会是这样的一个结果:function number function  很多人可能会抱着一种疑问的态度,为什么不是 undefined  function function ?

    在上面的代码中其实就涉及到了变量提升函数提升这个概念,在javascript引擎中,对于javascript代码的解析并不是从上往下,逐行进行解析的,而是以代码块进行解析:

    在相同作用域下,首先是将声明函数提升到代码的最顶端,其次就是变量提升,最后就是函数表达式,上述代码在javascript引擎中的解析就是可以看成如下:

    
    
    function hello(){//函数声明
    
    }
    console.log(typeof hello);//function
    var hello;
    hello = 123;
    console.log(typeof hello);//number
    var hello;
    hello = function(){}
    console.log(typeof hello);//function

    //function number function
    var hello = 123;的解析是先对变量hello进行定义,var hello;然后再给变量赋值,这里的var hello 就是对变量的一个提升。如:
    console.log(typeof hello);//undefined
    var
    hello = 123;
    console.log(typeof hello);//number

    //这里的变量hello被声明到作用域的顶端

    常见的例子还有:

    var hello = 123;
    function test(){
      console.log(hello);//undefined
      var hello = 'haha';
      console.log(hello);//haha
    }
    test();
    console.log(hello);//123
    //undefined haha 123

    在test函数的作用域下,由于hello 变量被提升,所以第一个console.log(hello);打印的就是undefined,第二个console.log(hello);打印的就是haha 

    最终结果就是 undefined haha 123

  • 相关阅读:
    打酱油
    一个在线演示代码运行的网站
    java数据结构之枚举
    tomcat ; nginx ;mysql
    restful demo 演示; jquery min1.1;
    rest规范 ; restful 风格; gradel介绍 ; idea安装 ;
    jetty;tomcat;热部署
    web容器 web服务器 servlet/jsp容器 之间的区别和关系是什么?
    jetty;linux 目录结构
    servlet;jsp;cookies;session
  • 原文地址:https://www.cnblogs.com/leijee/p/7567461.html
Copyright © 2011-2022 走看看