全局对象

一个全局对象是一个永远存在于 global scopeobject.

在 JavaScript 中, 有一个永远被定义的全局对象. 在一个 web 浏览器中, 当脚本创建全局变量时, 他们作为该全局对象的成员被创建. (In Node.js this is not the case.) The global object's interface depends on the execution context in which the script is running. For example:

  • In a web browser, any code which the script doesn't specifically start up as a background task has a Window as its global object. This is the vast majority of JavaScript code on the Web.
  • Code running in a Worker has a WorkerGlobalScope object as its global object.
  • Scripts running under Node.js have an object called global as their global object.

浏览器中的 window 对象

The window object is the Global Object in the Browser. Any Global Variables or Functions can be accessed as properties of the window object.

Access Global Variables

var foo = "foobar";
foo === window.foo; // Returns: true 

After defining a Global Variable foo, we can access its value directly from the window object, by using the variable name foo as a property name of the Global Object window.foo.

Explanation:

The global variable foo was stored in the window object, like this:

foo: "foobar"

Access Global Functions

function greeting() {
   console.log("Hi!");
}

window.greeting(); // It is the same as the normal invoking: greeting();

The example above explain how Global Functions are stored as properties in the window object. We created a Global Function greeting, then invoke it using the window object.

Explanation:

The global function greeting was stored in the window object, like this:

greeting: function greeting() {
   console.log("Hi!");
}