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 aWorkerGlobalScope
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论