LoginSignup
64
62

More than 5 years have passed since last update.

[JavaScript] グローバル変数とグローバルオブジェクトを取得する方法

Last updated at Posted at 2014-10-17

JavaScript のグローバル変数とグローバルオブジェクト

global.jpg

Webブラウザ上では window はグローバル変数だ。
そのプロパティは全てグローバル変数だ。
この window というグローバル変数は特別なオブジェクトでグローバルオブジェクトと呼ばれる。

var a = [];
for (var i in window) {
  if (window[i] === window) {
    a.push(i);
  }
}

console.log(a.join(', '));

シングルウィンドウの場合の結果。

self とか top とかも window と同じグローバルオブジェクトを指しているね。

結果(Chrome)
top, window, parent, frames, self 
結果(Firefox)
self, frames, parent, content, window, top
結果(ie9)
frames, parent, self, top, window 
結果(ie11)
frames, parent, self, top, window

Node.js のグローバル変数

Node.js の場合 global はグローバル変数だ。
そしてグローバルオブジェクトだ。
そのプロパティは全てグローバル変数だ。

var a = [];
for (var i in global) {
  if (global[i] === global) {
    a.push(i);
  }
}

console.log(a.join(', '));
結果
global, GLOBAL, root

ただ、それだけ。

ちなみに jrunscript とか jjs とか、 Java 系の JavaScript 内では、グローバルオブジェクトはどうやってポイントすればいいのだろうか。

JavaScript のグローバルオブジェクトを取得する方法は?

そう言えば普通に関数を呼べば this はグローバルオブジェクトだったよね。

get-this-test.js
  function getThis1() {
    return this;
  }
  function getThis2() {
    'use strict';
    return this;
  }
  console.log(typeof getThis1(), typeof getThis2());
  // -> object undefined

ES5の 'use strict' を使った Strict モードだと thisundefined という仕様だ。
ダメだ。

eval してみるか。

get-eval-this-test.js
  function getEval1() {
    return eval('this');
  }
  function getEval2() {
    'use strict';
    return eval('this');
  }
  console.log(typeof getEval1(), typeof getEval2());
  // -> object undefined

うまく行くわけ無いか。

関数リテラルの this はどうだ?

get-func-this-test.js
  function getFunc1() {
    return function(){ return this; }();
  }
  function getFunc2() {
    'use strict';
    return function(){ return this; }();
  }
  console.log(typeof getFunc1(), typeof getFunc2());
  // -> object undefined

一緒だね。

じゃあ new Function はどうだ?

get-global-test.js
  function getGlobal1() {
    return new Function('return this')();
  }
  function getGlobal2() {
    'use strict';
    return new Function('return this')();
  }
  console.log(typeof getGlobal1(), typeof getGlobal2());
  // -> object object

お、できたね。

何回も呼ぶと遅そうなので、繰り返し呼んでも既に取得済みのグローバルオブジェクトを返す様にしよう。

get-global.js
  var g = Function('return this')();
  function getGlobal() { return g; }
  console.log(typeof getGlobal());
  // -> object

完成。

と、思ったら get-global というのが npm にあった。
ほぼ同じだ。
でも、何度も呼ばれる事を考えると、変数は外に出しておく方が良いよね。

おしまい。

P.S.
2014/10/20: グローバル変数とグローバルオブジェクトを混同しない様に記述しなおした。

2018/12/13: globalThis というのができたみたい。Chrome 71 以降で。そのうち標準化されるかな。

64
62
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
64
62