グローバル変数は、グローバル変数window
に格納されます。あなただけの(関数のように)何も外にそれを宣言した場合、次のコードは動作します:
var test="stuff";
console.log(window.test);
同様の証明はwindow.location.href
はしかし、問題は、変数が宣言された場所にあるのかもしれないlocation.href
と同じであるということです。あなたが関数内でこの変数を宣言した場合、それはグローバルにのみ機能に存在し、そしてません。ここで
function foo(){
//declaring inside function
var test="stuff";
//undefined, since the variable exists in the function only
console.log(window.test);
//undefined, document refers to the document
//which is the top DOM object, not the global window
console.log(document.test);
//depends on what "this" refers to, especially
//when using call() or apply() to call the function
//For normal function calls, usually it points to window as well
console.log(this.test);
//none of the above refer to "test" that contains "stuff"
//because you are looking in the wrong place
}
簡単な答え:グローバル変数をどのように参照するかは、環境によって異なります。 –
「環境」とは、具体的にはどういう意味ですか?ブラウザ、スコープ、OS? – twiz
JavaScriptはブラウザ、Adobe Photoshop、古いVRMLブラウザ、Javaプログラムや他の多くのホストシステムに組み込むことができるエンジン内で実行できます。これらを「ホスト環境」と呼びます。だから、それはブラウザかもしれない。 JavaScriptプログラムは、これらの環境からオブジェクトを操作します。 –