Create an empty area?

Is there a way to define an area so that it is completely empty? Ideally, this will lead to being windowundefined. Or is it windowalways available in every permutation of regions? My initial idea was a bit of a line applywith an empty object in closure, but windowstill defined:

(function() {
    console.log(this); // an empty object
    console.log(window); // the window object is still defined
}).apply({});

Is there a way around the windowvariables associated with it, or am I just thinking funny right now?

+4
source share
1 answer

If you run javascript outside of the browser, you do not have to have a window object. For example, nodejs scripts do not have a window object, but they do have a global process object.

, , ...

(function(){ var window = undefined; console.log(this); console.log(window) }).apply({});

window, , .

, ...

(function(){ var window = undefined; (function(){
    console.log(this);
    console.log(window);
}).apply({}); })();

EDIT: ...

// create self invoking anonymous function
;(function(){
    // enumerate all global objects (`this` refers to current scope - assumed to be global at this point)
    var globals = Object.keys(this);
    // loop through all globals
    for(i in globals){
        // don't clobber the `console` global - we will need it!
        if(globals[i] !== "console"){
            // initialise local variable in current scope with name of every global
            eval("var " + globals[i]);
        };
    };
    // create scope with empty object for `this` and all globals reset
    ;(function(){
        console.log(this);
        console.log(window);
        /* for node.js, check process, not window ... */
        // console.log(process);
    }).apply({});
})();
+2

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


All Articles