5

Why is this code fine:

var test = {
    fn1: function(_origin, _componentType) {
        if(arguments.length > 1) throw "xx";
        // this strict is ok
        "use strict";

        var interface               = new Object(this);
    }
}

While this isn't

var test = {
    fn1: function(_origin, _componentType) {
        // This strict throws SyntaxError
        "use strict";

        if(arguments.length > 1) throw "xx";
        var interface               = new Object(this);
    }
}

I know interface is reserved word in strict mode, but shouldn't both examples throw an error?

Buksy
  • 11,571
  • 9
  • 62
  • 69

2 Answers2

10

"use strict"; needs to be the first statement in a function (or in a script, if script-wide) to trigger strict mode; anywhere else, you may as well be writing "merry christmas";.

Amadan
  • 191,408
  • 23
  • 240
  • 301
4

The first example doesn't actually enable strict mode. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Invoking_strict_mode:

Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing.

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • I'm sure this works as you describe, but it seems like a pretty brittle convention, prone to confusion like the OP's. Is there any explanation of why they did it like this? – chicks Nov 09 '15 at 07:57
  • @chicks Sorry, I don't know. It was obviously inspired by Perl's `use strict`, but that does work anywhere. Maybe it's easier to implement this way? – melpomene Nov 09 '15 at 07:59
  • Yet the Perl version allows you to `no strict` and `use strict` in the middle of things. Too bad people that steal from Perl steal only steal half of a feature. :) – chicks Nov 09 '15 at 08:02
  • 2
    @chicks: In Perl, `use strict` is a statement. In JavaScript, to avoid backward breakage, it is just a string, that is given special treatment. I am purely guessing here, but with the restriction, the parser needs to only check the first statement for special status. It also makes sure that programmers understand that it affects the *whole function*, not just the bit after it; for example, `function(x, x) { "use strict"; return x; }` does throw an error in JS even though the erroneous bit is technically before it; in Perl, `$foo = "foo"; use strict;` does not throw an error. – Amadan Nov 09 '15 at 08:43