【问题标题】:Possible variable hoisting issue可能的变量提升问题
【发布时间】:2014-01-13 17:32:52
【问题描述】:

考虑这个 JS(它在body 的末尾运行并导致错误)

(function(){
    "use strict";

    var div = document.getElementById("hook"),
        ul = div.firstElementChild,
        last_li = ul.lastElementChild;

    alert(div) // alerts "Uncaught TypeError: Cannot read property 'children' of undefined"  

})();

然后我删除了逗号并添加了 var 关键字,但收到了类似的错误(这不是 HTML):

(function(){
    "use strict";

    var div = document.getElementById("hook");
    var ul = div.firstElementChild;
    var last_li = ul.lastElementChild;

    alert(div) // alerts "Uncaught TypeError: Cannot read property 'lastElementChild' of undefined " 

})();

它的唯一工作方式是在div 赋值之后直接添加alert() 语句。我假设这与变量提升有关,但经验不足,无法确定。

有人可以简要介绍一下变量提升以及这里可能发生的情况吗?谢谢!

【问题讨论】:

  • 你能展示你的整个页面吗?你的代码对我来说很好:jsfiddle.net/MDRrL
  • 你可以只用谷歌提升,但这里有一个描述:adequatelygood.com/JavaScript-Scoping-and-Hoisting.html 这里似乎没有任何变量提升,代码和我一样工作得很好。
  • 技术上的吊装正在这里进行,但它对这里的任何东西都没有影响。

标签: javascript hoisting


【解决方案1】:

这不是吊装。

这里发生的事情如下:

(function(){
    "use strict";

    // this returns an element otherwise the next line would not work
    // that means the element is found in the DOM
    var div = document.getElementById("hook"), 
        // this returns the value `undefined` or `null` 
        ul = div.firstElementChild,
        // this is a TypeError, since `ul` is undefined
        last_li = ul.lastElementChild;

    alert(div) // we never actually get to this line
})();

你的元素可能没有元素(可能只是文本节点?)

这是fiddle reproducting the issue

这是fiddle where it works

【讨论】:

  • 谢谢。我确实有子元素,但它们被注释掉了——删除 cmets 后它按预期工作。
猜你喜欢
  • 1970-01-01
  • 2011-10-02
  • 2017-07-18
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多