Global object - MDN Web Docs Glossary: Definitions of Web-related terms 编辑

A global object is an object that always exists in the global scope.

In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (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 object in the Browser

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 explains how Global Functions are stored as properties in the window object. We created a Global Function called greeting, then invoked it using the window object.

Explanation:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:73 次

字数:3331

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文