Global Pollution Prevention

We are trying to implement the best JavaScript methods for the project we are working on, one of the limitations that we are trying to set is not pollution of the global area.

We have an HTML template used for each page, structured as follows:

<!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 to "lock" the object windowand prevent any addition to it (for example, var foo = 'foo';in the global scope or window['foo'] = 'foo';) before running the page scripts, but after loading the libraries.

I already looked Object.freeze, Object.sealbut they do not work for an object window(they cause an exception TypeError: can't change object extensibility).

I also looked at β€œcleanup” scenarios 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);

, .

? , JavaScript, , , .

P.s. , , , , , .

+4
1

var, .

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

.

Object.preventExtensions(window)
-1

Source: https://habr.com/ru/post/1530450/


All Articles