Should we use "use strict"; with third-party libraries (backbone, underscore)? How do we know that they are 'strict' compatible?

StackOverflow https://stackoverflow.com/questions/21728016

Вопрос

I've looked into a few libraries and it seems like they don't include the "use strict"; line on a file or function level. So if developers enable strict mode then how do we know if the library is compatible or not? There may be odd feature or browser specific issues that are not easily noticeable when strict mode is on and therefore missed until it's too late!

Это было полезно?

Решение

Of course, "use strict" can certainly be used at the top of a file of concatenated scripts (MDN), and so long as they are all strict-mode scripts, everything will be dandy: if not or there's a mix of strict/non-strict scripts, there's the possibility of errors being thrown that wouldn't normally be thrown.

The easiest way to work with it is to keep it in development and strip it out in production code: you know what things are supposed to do and have the ability to find/correct errors, so any strict-mode errors will only serve to improve your code. Once in production, strict mode really only serves to "break" your site for users with zero benefit to you unless they're savvy enough to debug and report it to you (not likely). Since strict-mode is a restricted form of javascript, relaxing your syntax is much more unlikely to cause errors than when you tightened it. (the major exception is eval which can begin "leaking" variables into the surrounding scope when strict-mode is removed).

Other than that, you can still concatenate scripts but wrap only strict-safe scripts in functions to use per-function strict mode. You don't have to do it per-atomic function in this case, just wrap the whole script(s) in a function:

(function(){
    "use strict"
    // My strict-mode script or scripts
})();

// non-strict safe scripts

It's not that many more characters when you consider that you only need to do it once and can stick all strict-mode scripts into that one function.

The disadvantage of having to explicitly export global vars out of the function is reduced, I find, by the fact that with strict-mode's aim to "never accidentally create global vars," I'm usually already specifying window for any variables I want global.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top