[英]why this code doesn't run?
(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();
})();
if not using var, the myList variable will supposedly be created as a globle variable. 如果不使用var,则myList变量将被创建为全局变量。 Either way, the code should be running. 无论哪种方式,代码都应该正在运行。 What is wrong with the code?? 代码有什么问题??
myList = ['one', 'two', 'three'];
In strict mode, you are not allowed to create global variables in this way. 在严格模式下,不允许您以这种方式创建全局变量。
From official Mozilla documentation - 来自Mozilla官方文档 -
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). 在正常的JavaScript错误输入中,赋值中的变量会在全局对象上创建一个新属性并继续“工作”(尽管未来可能会失败:可能在现代JavaScript中)。 Assignments which would accidentally create global variables instead throw in strict mode: 会意外创建全局变量的赋值会改为以严格模式抛出:
"use strict"; “严格使用”;
mistypedVaraible = 17; mistypedVaraible = 17; // throws a ReferenceError //引发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();
})();
You cannot set global variables like that when in strict mode. 在严格模式下,您无法设置类似的全局变量。
You'll have to do 你必须这样做
(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();
})();
By using "use strict"
you're limiting yourself to strict mode (which is a good thing), but that means you can't just use a variable that hasn't been set yet. 通过使用"use strict"
您将自己限制为严格模式(这是一件好事),但这意味着您不能只使用尚未设置的变量。
If you want to define myList
as a global variable, you'll have to do that before the function starts, so at the top of the script put: var myList;
如果要将myList
定义为全局变量,则必须在函数启动之前执行此操作,因此在脚本顶部放置: var myList;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.