Skip to content

Commit 802d106

Browse files
Merge pull request #181 from vplentinax/global-object
Global object
2 parents ea67503 + adbe14c commit 802d106

File tree

1 file changed

+34
-31
lines changed
  • 1-js/06-advanced-functions/05-global-object

1 file changed

+34
-31
lines changed
Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,90 @@
11

2-
# Global object
2+
# Objeto Global
33

4-
The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment.
4+
El objeto global proporciona variables y funciones que están disponibles en cualquier lugar. Por defecto, aquellas que están integradas en el lenguaje o el entorno.
55

6-
In a browser it is named `window`, for Node.js it is `global`, for other environments it may have another name.
6+
En un navegador se denomina `window`, para Node.js es` global`, para otros entornos puede tener otro nombre.
77

8-
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.
8+
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, como Chromium Edge, `globalThis` aún no es compatible, pero se puede usar mediante *polyfill*.
99

10-
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.
10+
Aquí usaremos `window`, suponiendo que nuestro entorno sea un navegador. Si su script puede ejecutarse en otros entornos, es mejor usar `globalThis` en su lugar.
1111

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

1414
```js run
1515
alert("Hello");
16-
// is the same as
16+
// es lo mismo que
1717
window.alert("Hello");
1818
```
1919

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

2222
```js run untrusted refresh
2323
var gVar = 5;
2424

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

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

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

3232
```js run untrusted refresh
3333
let gLet = 5;
3434

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

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

4040
```js run
4141
*!*
42-
// make current user information global, to let all scripts access it
42+
// Hacer que la información actual del usuario sea global, para que todos los scripts puedan acceder a ella
4343
window.currentUser = {
4444
name: "John"
4545
};
4646
*/!*
4747

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

51-
// or, if we have a local variable with the name "currentUser"
52-
// get it from window explicitly (safe!)
51+
// o, si tenemos una variable local con el nombre "currentUser"
52+
// obténgalo de la ventana explícitamente (¡seguro!)
5353
alert(window.currentUser.name); // John
5454
```
5555

56-
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.
56+
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 variables de "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.
5757

58-
## Using for polyfills
58+
## Uso para polyfills
5959

60-
We use the global object to test for support of modern language features.
60+
Usamos el objeto global para probar el soporte de las características del lenguaje moderno.
61+
62+
Por ejemplo, probar si existe un objeto `Promise` incorporado (no existe en navegadores muy antiguos):
6163

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

69-
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.
70+
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.
7071

7172
```js run
7273
if (!window.Promise) {
73-
window.Promise = ... // custom implementation of the modern language feature
74+
window.Promise = ... // implementación personalizada del lenguaje moderno
7475
}
7576
```
7677

77-
## Summary
78+
## Resumen
79+
80+
- El objeto global contiene variables que deberían estar disponibles en todas partes.
81+
82+
Eso incluye JavaScript incorporado, como `Array` y valores específicos del entorno, como ` window.innerHeight` -- la altura de la ventana en el navegador.
7883

79-
- The global object holds variables that should be available everywhere.
84+
- El objeto global tiene un nombre universal: `globalThis`.
8085

81-
That includes JavaScript built-ins, such as `Array` and environment-specific values, such as `window.innerHeight` -- the window height in the browser.
82-
- The global object has a universal name `globalThis`.
86+
... 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*).
8387

84-
...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).
85-
- We should store values in the global object only if they're truly global for our project. And keep their number at minimum.
86-
- In-browser, unless we're using [modules](info:modules), global functions and variables declared with `var` become a property of the global object.
87-
- To make our code future-proof and easier to understand, we should access properties of the global object directly, as `window.x`.
88+
- Deberíamos almacenar valores en el objeto global solo si son verdaderamente globales para nuestro proyecto. Y manteniendo su uso al mínimo.
89+
- 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.
90+
- 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`.

0 commit comments

Comments
 (0)