Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Global object#181

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
EzequielCaste merged 10 commits intojavascript-tutorial:masterfromvplentinax:global-object
Jun 24, 2020
Merged
Changes fromall commits
Commits
Show all changes
10 commits
Select commitHold shift + click to select a range
67e28ff
global-object
vplentinaxMay 11, 2020
351872e
Merge branch 'master' into global-object
vplentinaxJun 18, 2020
bd8d026
Update 1-js/06-advanced-functions/05-global-object/article.md
vplentinaxJun 24, 2020
4dc5c34
Update 1-js/06-advanced-functions/05-global-object/article.md
vplentinaxJun 24, 2020
da03b27
Update 1-js/06-advanced-functions/05-global-object/article.md
vplentinaxJun 24, 2020
cd63810
Update 1-js/06-advanced-functions/05-global-object/article.md
vplentinaxJun 24, 2020
5bebd2d
Update 1-js/06-advanced-functions/05-global-object/article.md
vplentinaxJun 24, 2020
f5dcbb3
Update 1-js/06-advanced-functions/05-global-object/article.md
vplentinaxJun 24, 2020
f0a887a
Update 1-js/06-advanced-functions/05-global-object/article.md
vplentinaxJun 24, 2020
adbe14c
Update 1-js/06-advanced-functions/05-global-object/article.md
vplentinaxJun 24, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 34 additions & 31 deletions1-js/06-advanced-functions/05-global-object/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,90 @@

#Global object
#Objeto Global

Theglobalobject providesvariablesand functions that are available anywhere. By default, those that are built into the language or the environment.
El objetoglobalproporcionavariablesy funciones que están disponibles en cualquier lugar. Por defecto, aquellas que están integradas en el lenguaje o el entorno.

In a browser it is named`window`,for Node.jsit is `global`,for other environments it may have another name.
En un navegador se denomina`window`,para Node.jses`global`,para otros entornos puede tener otro nombre.

Recently, `globalThis`was added to the language, as a standardized name for a global object, that should be supported across all environments. In some browsers, namely non-Chromium Edge, `globalThis`is not yet supported, but can be easily polyfilled.
Recientemente, `globalThis`se agregó al lenguaje, como un nombre estandarizado para un objeto global, que debería ser compatible con todos los entornos. En algunos navegadores, comoChromium Edge, `globalThis`aún no es compatible, pero se puede usar mediante *polyfill*.

We'll use `window` here, assuming that our environment is a browser. If your scriptmay run in other environments, it's better to use`globalThis`instead.
Aquí usaremos `window`, suponiendo que nuestro entorno sea un navegador. Si su scriptpuede ejecutarse en otros entornos, es mejor usar`globalThis`en su lugar.

All properties of the global object can be accessed directly:
Se puede acceder directamente a todas las propiedades del objeto global:

```js run
alert("Hello");
//is the same as
//es lo mismo que
window.alert("Hello");
```

In a browser, global functions and variablesdeclared with`var` (not `let/const`!)become the property of the global object:
En un navegador, las funciones y variablesglobales declaradas con`var` (¡**no**`let /const`!), se convierten en propiedad del objeto global:

```js run untrusted refresh
var gVar = 5;

alert(window.gVar); // 5 (became a property of the global object)
alert(window.gVar); // 5 (se convirtió en una propiedad del objeto global)
```

Please don't rely on that! This behavior exists for compatibility reasons. Modern scriptsuse [JavaScript modules](info:modules)where such thing doesn't happen.
¡Por favor no te fíes de eso! Este comportamiento existe por razones de compatibilidad. Los scriptsmodernos hacen uso de [Módulos Javascript](info:modules)para que tales cosas no sucedan.

If we used`let`instead, such thing wouldn't happen:
Si usáramos`let`en su lugar, esto no sucedería:

```js run untrusted refresh
let gLet = 5;

alert(window.gLet); // undefined (doesn't become a property of the global object)
alert(window.gLet); // undefined (no se convierte en una propiedad del objeto global)
```

If a value is so important that you'd like to make it available globally, write it directly as a property:
Si un valor es tan importante que desea que esté disponible globalmente, escríbalo directamente como una propiedad:

```js run
*!*
//make current user informationglobal,to let allscriptsaccess it
//Hacer que la información actual del usuario seaglobal,para que todos losscriptspuedan acceder a ella
window.currentUser = {
name: "John"
};
*/!*

//somewhere else in code
//en otro lugar en el código
alert(currentUser.name); // John

//or, if we have a localvariable with the name "currentUser"
//get it from window explicitly (safe!)
//o, si tenemos una variable localcon el nombre "currentUser"
//obténgalo de la ventana explícitamente (¡seguro!)
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" variablesand produces certain "outcome" is clearer, less prone to errors and easier to test than if it uses outer or global variables.
Dicho esto, generalmente se desaconseja el uso de variables globales. Debe haber la menor cantidad posible de ellas. El diseño del código donde una función obtiene variablesde "entrada" y produce cierto "resultado" es más claro, menos propenso a errores y más fácil de probar que si usa variables externas o globales.

##Using for polyfills
##Uso para polyfills

We use the global object to test for support of modern language features.
Usamos el objeto global para probar el soporte de las características del lenguaje moderno.

Por ejemplo, probar si existe un objeto `Promise` incorporado (no existe en navegadores muy antiguos):

For instance, test if a built-in `Promise` object exists (it doesn't in really old browsers):
```js run
if (!window.Promise) {
alert("Your browser is really old!");
}
```

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.
Si no hay ninguno (suponiendo que estamos en un navegador antiguo),podemos crear"polyfills":agregar funciones que no son compatibles con el entorno, pero que existen en el estándar moderno.

```js run
if (!window.Promise) {
window.Promise = ... //custom implementation of the modern language feature
window.Promise = ... //implementación personalizada del lenguaje moderno
}
```

## Summary
## Resumen

- El objeto global contiene variables que deberían estar disponibles en todas partes.

Eso incluye JavaScript incorporado, como `Array` y valores específicos del entorno, como ` window.innerHeight` -- la altura de la ventana en el navegador.

-Theglobalobject holds variables that should be available everywhere.
-El objetoglobaltiene un nombre universal: `globalThis`.

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`.
... Pero con mayor frecuencia se hace referencia a nombres específicos del entorno de la "vieja escuela", como `window` (navegador) y `global` (Node.js). Como `globalThis` es una propuesta reciente, no es compatible con Chromium Edge (pero sí mediante *polyfill*).

...But more often is referred by "old-school" environment-specific names, such as `window` (browser) and `global` (Node.js). As `globalThis` is a recent proposal, it's not supported in non-Chromium Edge (but can be polyfilled).
- 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](info: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`.
- Deberíamos almacenar valores en el objeto global solo si son verdaderamente globales para nuestro proyecto. Y manteniendo su uso al mínimo.
- En el navegador, a menos que estemos utilizando [módulos](info:modules), las funciones globales y las variables declaradas con `var` se convierten en una propiedad del objeto global.
- Para que nuestro código esté preparado para el futuro y sea más fácil de entender, debemos acceder a las propiedades del objeto global directamente, como `window.x`.

[8]ページ先頭

©2009-2025 Movatter.jp