ECMAScript 5 の Strict Mode でグローバルオブジェクトを得る
Strict Mode
ECMAScript 5 には Strict Mode という仕組みがあり、Strict Mode では様々な機能(誤解の元となる機能、危険な機能)が制限されています。Strcit Mode になると関数コード内で this === undefined
となり、this でグローバルオブジェクトを参照できません。
"use strict"; // Strict Mode を宣言する (function () { // グローバルコードで Strict Mode を宣言すると下位の関数コードも Strict Mode になる console.log(this); // undefined console.log(window); // [object Window] })();
ブラウザの JavaScript では window がグローバルオブジェクトですが、Node.js では global がグローバルオブジェクトになります。実装依存をなくすためには this を利用したいところです。
Strict Mode でグローバルオブジェクトを得る
グローバルコードでは this
がグローバルオブジェクトとなります。
"use strict"; console.log(this); // [object Window]
関数コードでは new Function()
を利用します。
"use strict"; (function () { console.log(new Function('return this')()); // [object Window] console.log(Function('return this')()); // [object Window] })();
実は ECMAScript 5 では "use strict";
が宣言されたとき、下位の 関数宣言(FunctionDeclaration
), 関数式(FunctionExpression
) も Strict Mode になると規定されており、new Function()
はその影響下にないのです。
http://es5.github.com/#x10.1.110.1.1 Strict Mode Code
...
- Function code that is part of a FunctionDeclaration, FunctionExpression, or accessor PropertyAssignment is strict function code if its FunctionDeclaration, FunctionExpression, or PropertyAssignment is contained in strict mode code or if the function code begins with a Directive Prologue that contains a Use Strict Directive.
そのため、new Function('return this')
は Strict Mode にならず、this
でグローバルオブジェクトを参照できます。
new Function() で Strict Mode にする
new Function()
でも "use strict";
を宣言すれば Strict Mode になります。
new Function('"use strict"; return this;')(); // undefined
JSON.parse
を利用できない実装でJSON文字列をパースする時など、どうしても new Function()
が必要な場合に Strict Mode にすれば比較的安全にコードを評価できます。