Is “use strict” Safe for Live Sites?

前端 未结 2 1932
小鲜肉
小鲜肉 2021-01-01 18:01

\"use strict\"; seems awesome, and we\'d really like to use it at our shop. However, we just want it so that we (the developers) can find strictness-issues; we very much DO

相关标签:
2条回答
  • 2021-01-01 18:29

    It's the latter. While beeing in strict mode, an Javascript interpreter may throw error messages at runtime, which would not get thrown in non-strict mode.

    On the other hand, most of these errors are "good errors", which means, they will actually help not breaking your code.

    For instance

    function foo() {
        "use strict";
        bar = true;
    }
    
    foo();
    

    This will throw

    "ReferenceError: assignment to undeclared variable bar"
    

    in strict mode, which is a good thing. In non strict mode, we would just have created a global variable called bar, which is probably not what we wanted. There are plenty of other situations where strict mode prevents the programmer from doing something stupid/bad/unwanted and throws error messages. But again, you want to have those errors instead of some wierd bugs.

    Have a further read on MDN

    0 讨论(0)
  • 2021-01-01 18:38

    If I understand you correctly, yes, it's definitely possible for strict mode to catch errors after the page has loaded. For example:

    'use strict';
    
    setTimeout(function() {
        undefined = 42; // Causes a TypeError
    }, 1000);
    
    // Click here for a demo.

    What you can do is pretty simple: you should be minifying your JavaScript when you move to production anyway. Just make sure that the 'use strict' gets removed during that minification process.

    Failing that, just try to make sure your code is strict-error-free. Strict mode usually comes into play with regards to semantics, not because of something odd the user input or even because of syntax. It shouldn't be too terribly difficult to catch all the cases. (But minifying and removing 'use strict' is a much better solution.)

    0 讨论(0)
提交回复
热议问题