简体   繁体   中英

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM