Is “use strict” Safe for Live Sites?

与世无争的帅哥 提交于 2019-11-29 17:34:50

问题


"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 NOT want to make our site break for our actual customers when it was working fine before.

Now, we could just use some server-side logic to achieve this:

{% if debug %}<script>"use strict";</script>{% endif %}

... except that "use strict" operates on a file-by-file basis, so that won't actually work (well, unless we start server-side processing all of our JS files).

So, my question is: do all the things "use strict" checks for get checked when the page loads, or is it possible for "use strict" to find errors after the page has loaded? If it's the former, we can just use "use strict" and stop worrying, because we'll load our site in development before loading it on live. However, if it's the latter we seem to be out of luck, as we can't test every possible runtime condition (and again, we don't want to make errors for our users when there were no errors before).


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/10115372/is-use-strict-safe-for-live-sites

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