|
1 | 1 |
|
2 |
| -# Global object |
| 2 | +# Objeto Global |
3 | 3 |
|
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. |
5 | 5 |
|
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. |
7 | 7 |
|
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*. |
9 | 9 |
|
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. |
11 | 11 |
|
12 |
| -All properties of the global object can be accessed directly: |
| 12 | +Se puede acceder directamente a todas las propiedades del objeto global: |
13 | 13 |
|
14 | 14 | ```js run
|
15 | 15 | alert("Hello");
|
16 |
| -// is the same as |
| 16 | +// es lo mismo que |
17 | 17 | window.alert("Hello");
|
18 | 18 | ```
|
19 | 19 |
|
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: |
21 | 21 |
|
22 | 22 | ```js run untrusted refresh
|
23 | 23 | var gVar = 5;
|
24 | 24 |
|
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) |
26 | 26 | ```
|
27 | 27 |
|
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. |
29 | 29 |
|
30 |
| -If we used `let` instead, such thing wouldn't happen: |
| 30 | +Si usáramos `let` en su lugar, esto no sucedería: |
31 | 31 |
|
32 | 32 | ```js run untrusted refresh
|
33 | 33 | let gLet = 5;
|
34 | 34 |
|
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) |
36 | 36 | ```
|
37 | 37 |
|
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: |
39 | 39 |
|
40 | 40 | ```js run
|
41 | 41 | *!*
|
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 |
43 | 43 | window.currentUser = {
|
44 | 44 | name: "John"
|
45 | 45 | };
|
46 | 46 | */!*
|
47 | 47 |
|
48 |
| -// somewhere else in code |
| 48 | +// en otro lugar en el código |
49 | 49 | alert(currentUser.name); // John
|
50 | 50 |
|
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!) |
53 | 53 | alert(window.currentUser.name); // John
|
54 | 54 | ```
|
55 | 55 |
|
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. |
57 | 57 |
|
58 |
| -## Using for polyfills |
| 58 | +## Uso para polyfills |
59 | 59 |
|
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): |
61 | 63 |
|
62 |
| -For instance, test if a built-in `Promise` object exists (it doesn't in really old browsers): |
63 | 64 | ```js run
|
64 | 65 | if (!window.Promise) {
|
65 | 66 | alert("Your browser is really old!");
|
66 | 67 | }
|
67 | 68 | ```
|
68 | 69 |
|
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. |
70 | 71 |
|
71 | 72 | ```js run
|
72 | 73 | if (!window.Promise) {
|
73 |
| - window.Promise = ... // custom implementation of the modern language feature |
| 74 | + window.Promise = ... // implementación personalizada del lenguaje moderno |
74 | 75 | }
|
75 | 76 | ```
|
76 | 77 |
|
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. |
78 | 83 |
|
79 |
| -- The global object holds variables that should be available everywhere. |
| 84 | +- El objeto global tiene un nombre universal: `globalThis`. |
80 | 85 |
|
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*). |
83 | 87 |
|
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