【问题标题】:weird variable hoisting in javascriptjavascript中奇怪的变量提升
【发布时间】:2020-05-31 08:55:45
【问题描述】:

所以我们知道用 var 关键字声明的变量是被提升的,如果我们在初始化之前尝试访问它们的值,我们会得到未定义的。但是,在下面记录 name 变量的代码中记录了函数而不是 undefined 为什么?

console.log(name);
console.log(lol);

var name = function(args = "Hello World"){
    console.log(args)
}

var lol = function(args = "Hello world") {
    console.log(args)
}

输出是

function(args = "Hello World"){
    console.log(args)
}

main.js:57 undefined

为什么名称变量未定义?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    作为根范围的窗口已经有一个名称属性。尝试以下操作并查看控制台中的输出。如果您单击链接,则打开的页面会将 MyWin 作为名称的输出。

    HTML (test.html)

    <head>
        <title>test</title>
    </head>
    
    <body>
        <a href="test.html" target="MyWin">Click me!</a>
        <script src="test.js"></script>
    </body>
    
    </html>
    

    Javascript (test.js)

    console.log("name", name);
    console.log("notname", notname);
    console.log("lol", lol);
    
    
    var notname = function (args = "Hello World") {
        console.log(args)
    }
    
    var lol = function (args = "Hello world") {
        console.log(args)
    }
    

    【讨论】:

      【解决方案2】:

      考虑代码

      console.log(test);
      
      var test = function(args = "Hello World"){
          console.log(args)
      }

      这将返回 undefined because only declarations are hoisted。也就是说,提升之后你的代码会是

      var test;
      console.log(test);
      
      test = function(args = "Hello World"){
          console.log(args)
      }

      【讨论】:

      • 我知道这件事。我不明白为什么名称不是未定义的。
      • pastebin.com/JbL89E6m 复制 html 并在浏览器中打开以查看此内容
      【解决方案3】:

      我认为你应该像那样记录你为什么困惑。

      console.log(name);
      console.log(lol);
      
      var name = function(args = "Hello World"){
          console.log(args)
      }
      
      var lol = function(args = "Hello world") {
          console.log(args)
      }
      
      console.log(name);
      console.log(lol);

      【讨论】:

      猜你喜欢
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 2021-11-19
      • 2015-01-01
      • 2014-12-31
      • 1970-01-01
      相关资源
      最近更新 更多