Prevent the pollution of the global scope

We're trying to enforce JavaScript best practices for the project we're working on, one of the limitations we're trying to set is to not pollute the global scope.

We have an HTML template used for every page structured like this:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <h1>Test</h1>
        <!-- Page content here -->
        <script src='https://code.jquery.com/jquery-2.1.0.js'></script>
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js'></script>
        <!-- Page scripts here -->
    </body>
</html>

What I'm trying to do is "lock" the window object and prevent any addition to it (eg var foo = 'foo'; in global scope or window['foo'] = 'foo'; ) before the page scripts runs but after the libraries have loaded.

I already looked at Object.freeze , Object.seal but they don't work for the window object (they raise a TypeError: can't change object's extensibility exception).

I also looked at "cleanup" scripts like these:

// Include this after the libraries.
(function(window) {
    var cache = {};
    for (var key in window) cache[key] = key;
    window.cache = cache;
})(window);

// Include this after all scripts.
(function(window) {
    var taint = {};
    for (var key in window) taint[key] = key;
    for (var key in window.cache) = delete taint[key];
    for (var key in taint) delete window[key];
})(window);

But they only clean-up the global scope, they don't prevent the pollution in the first space.

Is it possible to do it? We don't care if the solution breaks the JavaScript code polluting the global scope, we'll consider it a plus since it will force the developer to follow best practices.

Ps Yes, I do know the best solution would be code reviews, sadly they're not feasible in our situation so we're looking for a catch-all solution.


To lock global variables from the var keyword, wrap your code in an anonymous closure.

(function(){
  // ... Your code ...
}();

You can prevent assignment to window in chrome with the following.

Object.preventExtensions(window)
链接地址: http://www.djcxy.com/p/18342.html

上一篇: Chrome扩展程序隐藏/不显示

下一篇: 防止全球范围的污染