Javascript function global object

Global object

В JavaScript всегда определён глобальный объект. В веб-браузере, когда скрипты создают глобальные переменные, они создаются как свойства глобального объекта. (В Node.js это не так.) Interface глобального объекта зависит от контекста, в котором выполняется скрипт.К примеру:

  • В веб-браузере любой код, который не запускается скриптом явно как фоновую задачу, имеет Window в качестве своего глобального объекта. Это покрывает большую часть JavaScript-кода в сети.
  • Код, работающий в Worker имеет WorkerGlobalScope объект в качестве своего глобального объекта.
  • Скрипты, работающие в Node.js имеют объект, который называется global в качестве своего глобального объекта.

Объект window в Браузере

Объект window — Глобальный Объект в браузере. Доступ к любым Глобальным Переменным или функциям может быть получен как к свойствам объекта window .

Получение доступа к Глобальным Переменным

var foo = "foobar"; foo === window.foo; // Возвращает: true 

После определения Глобальной Переменной foo , мы можем получить доступ к его значению прямо с объекта window , использую имя переменной foo в качестве имени свойства Глобального Объекта window.foo .

Объяснение

Глобальная Переменная foo была сохранена в объекте window , подобно следующему примеру:

Получение доступа к Глобальным Функциям

function greeting()  console.log("Hi!"); > window.greeting(); // Тоже самое что и обычный вызов: greeting(); 

Пример выше показывает как Глобальные Функции хранятся в качестве свойств объекта window . Мы создали Глобальную Функцию greeting и вызвали её с помощью объекта window .

Объяснение

Глобальная функция greeting была сохранена в объекте window , подобно следующему примеру:

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

Found a content problem with this page?

This page was last modified on 20 июл. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Standard built-in objects

This chapter documents all of JavaScript’s standard, built-in objects, including their methods and properties.

The term «global objects» (or standard built-in objects) here is not to be confused with the global object. Here, «global objects» refer to objects in the global scope.

The global object itself can be accessed using the this operator in the global scope. In fact, the global scope consists of the properties of the global object, including inherited properties, if any.

Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference.

For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview.

Standard objects by category

Value properties

These global properties return a simple value. They have no properties or methods.

Function properties

These global functions—functions which are called globally, rather than on an object—directly return their results to the caller.

  • eval()
  • isFinite()
  • isNaN()
  • parseFloat()
  • parseInt()
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • escape() Deprecated
  • unescape() Deprecated

Fundamental objects

These objects represent fundamental language constructs.

Error objects

Error objects are a special type of fundamental object. They include the basic Error type, as well as several specialized error types.

Numbers and dates

These are the base objects representing numbers, dates, and mathematical calculations.

Text processing

These objects represent strings and support manipulating them.

Indexed collections

These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.

Keyed collections

These objects represent collections which use keys. The iterable collections ( Map and Set ) contain elements which are easily iterated in the order of insertion.

Structured data

These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).

Managing memory

These objects interact with the garbage collection mechanism.

Control abstraction objects

Control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example).

Reflection

Internationalization

Additions to the ECMAScript core for language-sensitive functionalities.

  • Intl
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.DisplayNames
  • Intl.DurationFormat
  • Intl.ListFormat
  • Intl.Locale
  • Intl.NumberFormat
  • Intl.PluralRules
  • Intl.RelativeTimeFormat
  • Intl.Segmenter

Found a content problem with this page?

This page was last modified on Apr 22, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Global object

The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment.

In a browser it is named window , for Node.js it is global , for other environments it may have another name.

Recently, globalThis was added to the language, as a standardized name for a global object, that should be supported across all environments. It’s supported in all major browsers.

We’ll use window here, assuming that our environment is a browser. If your script may run in other environments, it’s better to use globalThis instead.

All properties of the global object can be accessed directly:

alert("Hello"); // is the same as window.alert("Hello");

In a browser, global functions and variables declared with var (not let/const !) become the property of the global object:

var gVar = 5; alert(window.gVar); // 5 (became a property of the global object)

Function declarations have the same effect (statements with function keyword in the main code flow, not function expressions).

Please don’t rely on that! This behavior exists for compatibility reasons. Modern scripts use JavaScript modules where such a thing doesn’t happen.

If we used let instead, such thing wouldn’t happen:

let gLet = 5; alert(window.gLet); // undefined (doesn't become a property of the global object)

If a value is so important that you’d like to make it available globally, write it directly as a property:

// make current user information global, to let all scripts access it window.currentUser = < name: "John" >; // somewhere else in code alert(currentUser.name); // John // or, if we have a local variable with the name "currentUser" // get it from window explicitly (safe!) alert(window.currentUser.name); // John

That said, using global variables is generally discouraged. There should be as few global variables as possible. The code design where a function gets “input” variables and produces certain “outcome” is clearer, less prone to errors and easier to test than if it uses outer or global variables.

Using for polyfills

We use the global object to test for support of modern language features.

For instance, test if a built-in Promise object exists (it doesn’t in really old browsers):

If there’s none (say, we’re in an old browser), we can create “polyfills”: add functions that are not supported by the environment, but exist in the modern standard.

Summary

  • The global object holds variables that should be available everywhere. That includes JavaScript built-ins, such as Array and environment-specific values, such as window.innerHeight – the window height in the browser.
  • The global object has a universal name globalThis . …But more often is referred by “old-school” environment-specific names, such as window (browser) and global (Node.js).
  • We should store values in the global object only if they’re truly global for our project. And keep their number at minimum.
  • In-browser, unless we’re using modules, global functions and variables declared with var become a property of the global object.
  • To make our code future-proof and easier to understand, we should access properties of the global object directly, as window.x .

Comments

  • If you have suggestions what to improve — please submit a GitHub issue or a pull request instead of commenting.
  • If you can’t understand something in the article – please elaborate.
  • To insert few words of code, use the tag, for several lines – wrap them in tag, for more than 10 lines – use a sandbox (plnkr, jsbin, codepen…)

Источник

Глобальный объект

Глобальный объект предоставляет переменные и функции, доступные в любом месте программы. По умолчанию это те, что встроены в язык или среду исполнения.

В браузере он называется window , в Node.js — global , в другой среде исполнения может называться иначе.

Недавно globalThis был добавлен в язык как стандартизированное имя для глобального объекта, которое должно поддерживаться в любом окружении. Он поддерживается во всех основных браузерах.

Далее мы будем использовать window , полагая, что наша среда – браузер. Если скрипт может выполняться и в другом окружении, лучше будет globalThis .

Ко всем свойствам глобального объекта можно обращаться напрямую:

alert("Привет"); // это то же самое, что и window.alert("Привет");

В браузере глобальные функции и переменные, объявленные с помощью var (не let/const !), становятся свойствами глобального объекта:

var gVar = 5; alert(window.gVar); // 5 (становится свойством глобального объекта)

То же самое касается функций, объявленных с помощью синтаксиса Function Declaration (выражения с ключевым словом function в основном потоке кода, не Function Expression)

Пожалуйста, не полагайтесь на это. Такое поведение поддерживается для совместимости. В современных проектах, использующих JavaScript-модули, такого не происходит.

Если бы мы объявили переменную при помощи let , то такого бы не произошло:

let gLet = 5; alert(window.gLet); // undefined (не становится свойством глобального объекта)

Если свойство настолько важное, что вы хотите сделать его доступным для всей программы, запишите его в глобальный объект напрямую:

// сделать информацию о текущем пользователе глобальной, для предоставления доступа всем скриптам window.currentUser = < name: "John" >; // где угодно в коде alert(currentUser.name); // John // или, если у нас есть локальная переменная с именем "currentUser", // получим её из window явно (безопасно!) alert(window.currentUser.name); // John

При этом обычно не рекомендуется использовать глобальные переменные. Следует применять их как можно реже. Дизайн кода, при котором функция получает входные параметры и выдаёт определённый результат, чище, надёжнее и удобнее для тестирования, чем когда используются внешние, а тем более глобальные переменные.

Использование для полифилов

Глобальный объект можно использовать, чтобы проверить поддержку современных возможностей языка.

Например, проверить наличие встроенного объекта Promise (такая поддержка отсутствует в очень старых браузерах):

Если нет (скажем, используется старый браузер), мы можем создать полифил: добавить функции, которые не поддерживаются окружением, но существуют в современном стандарте.

Итого

  • Глобальный объект хранит переменные, которые должны быть доступны в любом месте программы. Это включает в себя как встроенные объекты, например, Array , так и характерные для окружения свойства, например, window.innerHeight – высота окна браузера.
  • Глобальный объект имеет универсальное имя – globalThis . …Но чаще на него ссылаются по-старому, используя имя, характерное для данного окружения, такое как window (браузер) и global (Node.js).
  • Следует хранить значения в глобальном объекте, только если они действительно глобальны для нашего проекта. И стараться свести их количество к минимуму.
  • В браузерах, если только мы не используем модули, глобальные функции и переменные, объявленные с помощью var , становятся свойствами глобального объекта.
  • Для того, чтобы код был проще и в будущем его легче было поддерживать, следует обращаться к свойствам глобального объекта напрямую, как window.x .

Источник

Читайте также:  Java program to find java version
Оцените статью