From 67e28ff08c32f107dc404f40a1dfd09ea8621597 Mon Sep 17 00:00:00 2001 From: vplentinax Date: Mon, 11 May 2020 18:47:18 -0400 Subject: [PATCH 1/9] global-object --- .../05-global-object/article.md | 183 ++++++------------ 1 file changed, 59 insertions(+), 124 deletions(-) diff --git a/1-js/06-advanced-functions/05-global-object/article.md b/1-js/06-advanced-functions/05-global-object/article.md index 4d480a039..5d002094a 100644 --- a/1-js/06-advanced-functions/05-global-object/article.md +++ b/1-js/06-advanced-functions/05-global-object/article.md @@ -1,155 +1,90 @@ -# Global object +# Objeto Global -The global object provides variables and functions that are available anywhere. Mostly, the ones that are built into the language or the host environment. +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. -In a browser it is named "window", for Node.JS it is "global", for other environments it may have another name. +En un navegador se denomina `window`, para Node.js es` global`, para otros entornos puede tener otro nombre. -For instance, we can call `alert` as a method of `window`: +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*. + +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. + +Se puede acceder directamente a todas las propiedades del objeto global: ```js run alert("Hello"); - -// the same as +// es lo mismo que window.alert("Hello"); ``` -We can reference other built-in functions like `Array` as `window.Array` and create our own properties on it. - -## Browser: the "window" object - -For historical reasons, in-browser `window` object is a bit messed up. - -1. It provides the "browser window" functionality, besides playing the role of a global object. - - We can use `window` to access properties and methods, specific to the browser window: - - ```js run - alert(window.innerHeight); // shows the browser window height - - window.open('http://google.com'); // opens a new browser window - ``` - -2. Top-level `var` variables and function declarations automatically become properties of `window`. - - For instance: - ```js untrusted run no-strict refresh - var x = 5; - - alert(window.x); // 5 (var x becomes a property of window) - - window.x = 0; - - alert(x); // 0, variable modified - ``` - - Please note, that doesn't happen with more modern `let/const` declarations: - - ```js untrusted run no-strict refresh - let x = 5; - - alert(window.x); // undefined ("let" doesn't create a window property) - ``` - -3. Also, all scripts share the same global scope, so variables declared in one ` +```js run untrusted refresh +var gVar = 5; - - ``` - -4. And, a minor thing, but still: the value of `this` in the global scope is `window`. - - ```js untrusted run no-strict refresh - alert(this); // window - ``` - -Why was it made like this? At the time of the language creation, the idea to merge multiple aspects into a single `window` object was to "make things simple". But since then many things changed. Tiny scripts became big applications that require proper architecture. - -Is it good that different scripts (possibly from different sources) see variables of each other? - -No, it's not, because it may lead to naming conflicts: the same variable name can be used in two scripts for different purposes, so they will conflict with each other. - -As of now, the multi-purpose `window` is considered a design mistake in the language. - -Luckily, there's a "road out of hell", called "Javascript modules". - -If we set `type="module"` attribute on a ` - ``` +Si usáramos `let` en su lugar, esto no sucedería: -- Two modules that do not see variables of each other: +```js run untrusted refresh +let gLet = 5; - ```html run - +alert(window.gLet); // undefined (no se convierte en una propiedad del objeto global) +``` - - ``` +Si un valor es tan importante que desea que esté disponible globalmente, escríbalo directamente como una propiedad: -- And, the last minor thing, the top-level value of `this` in a module is `undefined` (why should it be `window` anyway?): +```js run +*!* +// Hacer que la información actual del usuario sea global, para que todos los scripts puedan acceder a ella +window.currentUser = { + name: "John" +}; +*/!* + +// en otro lugar en el código +alert(currentUser.name); // John + +// o, si tenemos una variable local con el nombre "currentUser" +// obténgalo de la ventana explícitamente (¡seguro!) +alert(window.currentUser.name); // John +``` - ```html run - - ``` +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. -**Using `