javascript “use strict” and Nick's find global function

元气小坏坏 提交于 2019-11-27 22:29:02

Access to the Global Object (before ES5)

If you need to access the global object without hard-coding the identifier window, you can do the following from any level of nested function scope:

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

This way you can always get the global object, because inside functions that were invoked as functions (that is, not as constrictors with new) this should always point to the global object.

This is actually no longer the case in ECMAScript 5 in strict mode, so you have to adopt a different pattern when your code is in strict mode.

For example, if you’re developing a library, you can wrap your library code in an immediate function (discussed in Chapter 4) and then from the global scope, pass a reference to this as a parameter to your immediate function.

Access to the Global Object (after ES5)

Commonly, the global object is passed as an argument to the immediate function so that it’s accessible inside of the function without having to use window: this way makes the code more interoperable in environments outside the browser:

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

“JavaScript Patterns, by Stoyan Stefanov (O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”

CoolAJ86

Solution:

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

Works in all Browsers, Engines, ES3, ES5, strict, nested scope, etc.

A slight variation will pass JSLINT:

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

Discussion

See How to get the global object in JavaScript?

Here's a snippet from Perfection Kills, using global eval.

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

ECMA3, ECMA5, Strict mode, etc compatible, passes JSLint.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!