Javascript "use strict" and Nick find global function

Thus, I saw a function that was absolutely frankly beautiful in its simplicity, since it allowed you to find a global object (which, depending on the environment at that time, could not be a window), while inside an anonymous function; however, when you throw javascripts "use strict"; mode crashes due to a change in the 'this' keyword. There were several ways to do this?

(function () { var win = function () { return (function () { return this; }()); }; //win now points to the global object no matter where it is called. }()); 

Now, if they are called in the context of "use strict", we lose the described functionality, is there any equivalent that can be done in ES5 strict mode?

For reference

 (function () { "use strict" //code here is in strict mode }()) 
+7
source share
3 answers

Global Object Access (up to ES5)

If you need to access a global object without hard coding the identifier window, you can do the following from any level in the nested function area:

 var global = (function () { return this; }()); 

Thus, you can always get a global object, because functions that are called inside as functions (i.e. not as constrictors with new ones), this should always point to a global object.

This is actually not the case in ECMAScript 5 in strict mode, so you need to accept a different template when your code is in strict mode.

For example, if you are developing a library, you can instantly wrap your library code (discussed in Chapter 4), and then from a global scope, pass a link to this as a parameter for your immediate function.

Access to the global object (after ES5)

Usually, a global object is passed as an argument to a direct function, therefore its accessible inside a function without using a window: thus, the code is more compatible in environments outside the browser:

 (function (global) { // access the global object via `global` }(this)); 

"JavaScript Templates, Stoyan Stefanov (OReilly). Copyright 2010 Yahoo !, Inc., 9780596806750."

+8
source

Decision:

 var global = Function('return this')(); 

Works in all browsers, engines, ES3, ES5, strict, nested area, etc.

A small variation will go through JSLINT:

 var FN = Function, global = FN('return this')(); 

Discussion

See How to get a global object in JavaScript?

+8
source

Here is a snippet from Perfection Kills using global eval.

 var root = (function () { return this || (0 || eval)('this'); }()); 

ECMA3, ECMA5, strict mode, etc., reports JSLint.

+1
source

All Articles