Is “use strict” Safe for Live Sites?

試著忘記壹切 提交于 2019-11-30 11:38:24

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!