2013-11-21 99 views
2
(function() { 
    "use strict"; 


    function initialize() { 
     myList = ['one', 'two', 'three']; 
    } 

    function displayList() { 
     var i, n; 
     for (i = 0, n = myList.length; i < n; i += 1) { 
      alert(myList[i]); 
     } 
    } 
    initialize(); 
    displayList(); 

})(); 

如果不使用var,myList變量應該被創建爲全局變量。無論哪種方式,代碼應該運行。代碼有什麼問題?爲什麼這段代碼無法運行?

+0

看到這裏http://stackoverflow.com/問題/ 9397778/how-to-declare-global-variables-when-strict-mode-pragma –

+0

你會得到什麼錯誤信息? – Wyzard

+0

我在jsfiddle中運行這段代碼;我沒有得到任何錯誤信息... – Joshua

回答

7
myList = ['one', 'two', 'three']; 

在嚴格模式下,您不允許以這種方式創建全局變量。

從Mozilla官方documentation -

First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). Assignments which would accidentally create global variables instead throw in strict mode:

"use strict";

mistypedVaraible = 17; // throws a ReferenceError

This works -

(function() { 
    "use strict"; 

    var myList; 

    function initialize() { 
     myList = ['one', 'two', 'three']; 
    } 

    function displayList() { 
     var i, n; 
     for (i = 0, n = myList.length; i < n; i += 1) { 
      alert(myList[i]); 
     } 
    } 

    initialize(); 
    displayList(); 
})(); 
0

嚴格模式時,您不能設置全局變量這樣。

你必須做

(function() { 
    "use strict"; 

    var myList; 

    function initialize() { 
     myList = ['one', 'two', 'three']; 
    } 

    function displayList() { 
     var i, n; 
     for (i = 0, n = myList.length; i < n; i += 1) { 
      alert(myList[i]); 
     } 
    } 
    initialize(); 
    displayList(); 

})(); 
0

使用"use strict"你限制自己,以嚴格的模式(這是一件好事),但是這意味着你不能只使用不是招」的變量還沒有設置。

如果要定義myList作爲一個全局變量,你必須做到這一點的功能開始之前,所以在腳本上面放:var myList;

相關問題