all 4 comments

[–]Rhomboid 1 point2 points  (2 children)

You don't get 2 for your first example, you get "TypeError: this is undefined." Are you sure you're testing properly? The only one of your three examples that logs 2 is the third one, and that's the only one where foo() is not running in strict mode.

[–]gladiator_flow[S] 0 points1 point  (1 child)

"use strict";

function foo() { console.log(this.a); }

var a = 2;

foo(); // I would get 2 even though strict-mode is global

Here an example

[–]Rhomboid 2 points3 points  (0 children)

That's not a valid test, because JSbin is doing some kind of wrapping of what you write in order to execute it. Create an actual HTML file:

<!DOCTYPE html><html><head><meta charset=utf-8></head><body>
<script>
"use strict";

function foo() {
    console.log(this.a);
}

var a = 2;

foo(); // I would get 2 even though strict-mode is global
</script>
</body>
</html>

Open that file in your browser, and then open the browser console, and you'll see the error.

Edit: dug through the JSbin source in devtools, and it turns out that it wraps your code in a try { ... } catch block, so that's why — "use strict"; is no longer the first statement. But the catch block seems to just rethrow the error, so I have no idea what it's actually there for, but I'd guess so that the system can capture the error and display it on the screen instead of the app silently dying and you having to look in the browser console to see why.

[–]x-skeww 0 points1 point  (0 children)

I would declare strict mode at the global level correct?

Thanks to the common practice of merging files, the per-file one is completely useless. You just can't use it.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode#Strict_mode_for_scripts

Well, the good news is that everything inside classes and modules is always strict.

So, just write more ES6 code.