最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript 'strict mode' not working as expected? - Stack Overflow

programmeradmin0浏览0评论
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. I thought 'strict' mode would catch it but it didn't. Shouldn't this throw an error in this case?

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. I thought 'strict' mode would catch it but it didn't. Shouldn't this throw an error in this case?

Share Improve this question edited Jun 30, 2015 at 2:02 Boann 50k16 gold badges124 silver badges152 bronze badges asked Jun 28, 2015 at 11:18 JS-JMS-WEBJS-JMS-WEB 2,6253 gold badges18 silver badges26 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 25

A name global variable already exists, unrelated to your code; 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.

Super confusing :D

  • window.name on MDN.
  • HTML Specification, window name property.

"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.

发布评论

评论列表(0)

  1. 暂无评论