zoukankan      html  css  js  c++  java
  • With or without var keyword

    Question:

    What exactly is the function of the var keyword in Javascript, and what is the difference between:

    var someNumber =2;
    var someFunction =function(){ doSomething;}
    var someObject ={}
    var someObject.someProperty =5;
    

      

    and:

    someNumber =2;
    someFunction =function(){ doSomething;}
    someObject ={}
    someObject.someProperty =5;
    

      

    When would you use either one, and why/what does it do?

    Answer:

    If you're in the global scope then there's no difference.

    If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):

    // These are both globals
    var foo = 1;
    bar = 2;
    
    function()
    {
        var foo = 1; // Local
        bar = 2;     // Global
    
        // Execute an anonymous function
        (function()
        {
            var wibble = 1; // Local
            foo = 2; // Inherits from scope above (creating a closure)
            moo = 3; // Global
        }())
    }
    

      If you're not doing an assignment then you need to use var:

    var x; // Declare x
    

      

  • 相关阅读:
    nginx配置虚拟主机
    Nginx 目录结构
    Day 12.1模拟赛游记
    Day 11.25模拟赛游记
    Day 11.20模拟赛游记
    Day 11.19模拟赛游记
    Day 11.17模拟赛游记
    【题解报告】P3797 妖梦斩木棒
    8-28练习报告
    二分图匹配与树链剖分
  • 原文地址:https://www.cnblogs.com/malaikuangren/p/2933082.html
Copyright © 2011-2022 走看看