执行上下文混乱

时间:2014-11-03 14:38:06

标签: javascript scope

我知道JavaSript没有块级范围,所以为什么JShint会抛出这个错误:

可能尚未初始化变量warning

function x(){
   if(y<allQuestions.length && document.getElementById('warning')<1) {
        var warning = document.createElement('p');
        warning.id = 'warning';
        warning.appendChild(document.createTextNode('Please check an answer!'));
        wrapper.appendChild(warning);

        setTimeout(function(){
            if (document.getElementById('warning')) {
                wrapper.removeChild(document.getElementById('warning'));
            }
        }, 2500);

    }else{
         //HERE is the problem
         warning.appendChild(document.createTextNode('Your response is still worng!'));

    }
}

如果没有else statemenet,它会识别变量并且代码可以正常工作。

1 个答案:

答案 0 :(得分:0)

这是JSHint完全正确的情况。想想您的代码:warning在哪里声明并初始化?如果代码进入else子句,warning将如何获得值?

var声明和初始化移出if块:

function x(){
    var warning = document.createElement('p');
    if (y<allQuestions.length && document.getElementById('warning')<1) {

请记住,变量声明被提升到函数顶部,但变量初始化不是。因此,您的原始代码相当于:

function x(){
    var warning;
    if (y<allQuestions.length && document.getElementById('warning')<1) {
      warning = document.createElement('p');
      // ...
相关问题