Search code examples
javascriptecmascript-5strict

JavaScript 'use strict'; inside functions


Tested some js code in Chrome Dev Console and I'm a bit confused.

I know that in strict mode functions that are not methods of an object when referred to this keyword should receive undefined instead of global object.

function test(){
    "use strict";
    return this===undefined;}
test(); 

Outputs false.

"use strict";
function test(){
    return this===undefined;}
test(); 

Still false.

(function test(){
    "use strict";
    return this===undefined;}());

Outputs true.

Just wanted to clarify. ʕ •ᴥ•ʔ I'm new to js.


Solution

  • It is a bug in the Chromium Developer Console that causes this to still refer to the global object. The same code works as specified with javascript: in the location bar, and in documents.

    You can test that like so (2 console inputs):

    var global = (function () { return this; }());
    
    "use strict";
    function test () { return this === global; }
    test();
    

    and (one or more console inputs)

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.appendChild(document.createTextNode(
      'function test () { "use strict"; return this === undefined; }; console.log(test());'
    ));
    document.body.appendChild(script);
    

    Tested in Chromium Version 25.0.1364.97 Debian 7.0 (183676).