[英]JavaScript 'strict mode' not working as expected?
var test = function() {
'use strict';
var mapNames = {
'name': 'City Name:',
'coord.lat': 'Latitute:'
};
for (var key in mapNames) {
var names;
if (mapNames[key]) {
name = mapNames[key];
} else {
name = key;
}
}
console.log(name);
}
test();
In the code above I made a mistake by declaring variable names
and using name
instead. 在上面的代码中,我通过声明变量names
和使用name
而犯了一个错误。 I thought 'strict' mode would catch it but it didn't. 我认为'严格'模式会抓住它,但事实并非如此。 Shouldn't this throw an error in this case? 在这种情况下,这不应该抛出错误吗?
A name
global variable already exists, unrelated to your code; name
全局变量已存在,与您的代码无关; it represents the name of the current window, so you are assigning to an already existing variable. 它表示当前窗口的名称,因此您将分配给现有的变量。
window.name; // the name of the current window for cross-window communication
Everything on window
is declared as a global - so it is not reference-erroring since it is assigning to a variable in an outer scope. window
上的所有内容都被声明为全局 - 因此它不是引用错误,因为它分配给外部作用域中的变量。
Super confusing :D 超级混乱:D
window.name
on MDN. MDN上的window.name
。 "use strict"
would prevent defining new global variables, here we are performing an assignment to an existing variable, think of it as name
is in the global scope, like window.Blob
, window.console
and so on. "use strict"
会阻止定义新的全局变量,这里我们正在对现有变量执行赋值,将其视为name
在全局范围内,如window.Blob
, window.console
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.