Skip to content

Commit b49fe5f

Browse files
authored
Merge pull request #123 from anapaulalemos/globalObject
Global object
2 parents e6b9035 + bce20f9 commit b49fe5f

File tree

1 file changed

+61
-129
lines changed
  • 1-js/06-advanced-functions/05-global-object

1 file changed

+61
-129
lines changed
Lines changed: 61 additions & 129 deletions
Original file line numberDiff line numberDiff line change
@@ -1,155 +1,87 @@
11

2-
# Global object
2+
# Objeto global
33

4-
The global object provides variables and functions that are available anywhere. Mostly, the ones that are built into the language or the host environment.
4+
O objeto global fornece variáveis e funções que estão disponíveis em qualquer lugar. Em sua maioria, aqueles que são incorporados ao idioma ou ao ambiente.
55

6-
In a browser it is named "window", for Node.js it is "global", for other environments it may have another name.
6+
No navegador ele é chamado de `window`, no Node.js é `global`, em outros ambientes pode ter outro nome.
77

8-
For instance, we can call `alert` as a method of `window`:
8+
Recentemente, `globalThis` foi adicionado a linguagem como um nome padrão para o objeto global, que deve ser suportado em todos os ambientes. Em alguns navegadores, como o "non-Chromium Edge", `globalThis` ainda não é suportado, mas pode ser facilmente utilizado através de um polyfill.
99

10-
```js run
11-
alert("Hello");
12-
13-
// the same as
14-
window.alert("Hello");
15-
```
16-
17-
We can reference other built-in functions like `Array` as `window.Array` and create our own properties on it.
18-
19-
## Browser: the "window" object
20-
21-
For historical reasons, in-browser `window` object is a bit messed up.
22-
23-
1. It provides the "browser window" functionality, besides playing the role of a global object.
24-
25-
We can use `window` to access properties and methods, specific to the browser window:
26-
27-
```js run
28-
alert(window.innerHeight); // shows the browser window height
29-
30-
window.open('http://google.com'); // opens a new browser window
31-
```
32-
33-
2. Top-level `var` variables and function declarations automatically become properties of `window`.
34-
35-
For instance:
36-
```js untrusted run no-strict refresh
37-
var x = 5;
38-
39-
alert(window.x); // 5 (var x becomes a property of window)
40-
41-
window.x = 0;
42-
43-
alert(x); // 0, variable modified
44-
```
45-
46-
Please note, that doesn't happen with more modern `let/const` declarations:
47-
48-
```js untrusted run no-strict refresh
49-
let x = 5;
50-
51-
alert(window.x); // undefined ("let" doesn't create a window property)
52-
```
53-
54-
3. Also, all scripts share the same global scope, so variables declared in one `<script>` become visible in another ones:
10+
Usamos `window` aqui, assumindo que nosso ambiente seja um navegador. Se o seu script puder ser executado em outros ambientes, é melhor utilizar o `globalThis`.
5511

56-
```html run
57-
<script>
58-
var a = 1;
59-
let b = 2;
60-
</script>
12+
Todas as propriedades do objeto global podem ser acessadas diretamente:
6113

62-
<script>
63-
alert(a); // 1
64-
alert(b); // 2
65-
</script>
66-
```
67-
68-
4. And, a minor thing, but still: the value of `this` in the global scope is `window`.
69-
70-
```js untrusted run no-strict refresh
71-
alert(this); // window
72-
```
73-
74-
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.
75-
76-
Is it good that different scripts (possibly from different sources) see variables of each other?
77-
78-
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.
79-
80-
As of now, the multi-purpose `window` is considered a design mistake in the language.
81-
82-
Luckily, there's a "road out of hell", called "JavaScript modules".
83-
84-
If we set `type="module"` attribute on a `<script>` tag, then such script is considered a separate "module" with its own top-level scope (lexical environment), not interfering with `window`.
85-
86-
- In a module, `var x` does not become a property of `window`:
14+
```js run
15+
alert("Olá");
16+
// é o mesmo que
17+
window.alert("Olá");
18+
```
8719

88-
```html run
89-
<script type="module">
90-
var x = 5;
20+
No navegador, funções e variáveis globais declaradas com `var` (não `let/const`!) tornam-se propriedades do objeto global:
9121

92-
alert(window.x); // undefined
93-
</script>
94-
```
22+
```js run untrusted refresh
23+
var gVar = 5;
9524

96-
- Two modules that do not see variables of each other:
25+
alert(window.gVar); // 5 (se torna uma propriedade do objeto global)
26+
```
9727

98-
```html run
99-
<script type="module">
100-
let x = 5;
101-
</script>
28+
Por favor, não confie nisso! Esse comportamento existe por motivos de compatibilidade. Scripts modernos usam [JavaScript modules](info:modules) onde tal coisa não acontece.
10229

103-
<script type="module">
104-
alert(window.x); // undefined
105-
alert(x); // Error: undeclared variable
106-
</script>
107-
```
30+
Se usássemos `let`, isso não aconteceria:
10831

109-
- And, the last minor thing, the top-level value of `this` in a module is `undefined` (why should it be `window` anyway?):
32+
```js run untrusted refresh
33+
let gLet = 5;
11034

111-
```html run
112-
<script type="module">
113-
alert(this); // undefined
114-
</script>
115-
```
35+
alert(window.gLet); // undefined (não se torna uma propriedade do objeto global)
36+
```
11637

117-
**Using `<script type="module">` fixes the design flaw of the language by separating top-level scope from `window`.**
38+
Se um valor é tão importante que você gostaria de deixá-lo disponível globalmente, escreva-o diretamente como uma propriedade.
11839

119-
We'll cover more features of modules later, in the chapter [](info:modules).
40+
```js run
41+
*!*
42+
// tornando globais as informações de current user, para permitir que todos os script as acessem
43+
window.currentUser = {
44+
name: "John"
45+
};
46+
*/!*
47+
48+
// em outro lugar no código
49+
alert(currentUser.name); // John
50+
51+
// ou, se tivermos um variável local com o nome "currentUser"
52+
// a obtenha explicitamente do window (seguro!)
53+
alert(window.currentUser.name); // John
54+
```
12055

121-
## Valid uses of the global object
56+
Dito isto, o uso de variáveis globais é geralmente desencorajado. Deve haver o menor número possível de variáveis globais. O design do código onde uma função recebe variáveis de entrada e produz certos resultados é mais claro, menos propenso a erros e mais fácil de testar do que se usar varáveis externas ou globais.
12257

123-
1. Using global variables is generally discouraged. There should be as few global variables as possible, but if we need to make something globally visible, we may want to put it into `window` (or `global` in Node.js).
58+
## Usando para polyfills
12459

125-
Here we put the information about the current user into a global object, to be accessible from all other scripts:
60+
Usamos o objeto global para testar o suporte aos recursos modernos da linguagem.
12661

127-
```js run
128-
// explicitly assign it to `window`
129-
window.currentUser = {
130-
name: "John",
131-
age: 30
132-
};
62+
Por exemplo, testar se o objeto `Promise` nativo existe (ele não existe em navegadores antigos):
63+
```js run
64+
if (!window.Promise) {
65+
alert("Seu navegador é muito antigo!");
66+
}
67+
```
13368

134-
// then, elsewhere, in another script
135-
alert(window.currentUser.name); // John
136-
```
69+
Se não houver (vamos dizer que estamos em um navegador antigo), podemos criar "polyfills": adicionar funções que não são suportadas pelo ambiente, mas existem no padrão moderno.
13770

138-
2. We can test the global object for support of modern language features.
71+
```js run
72+
if (!window.Promise) {
73+
window.Promise = ... // implementação customizada do recurso moderno da linguagem
74+
}
75+
```
13976

140-
For instance, test if a build-in `Promise` object exists (it doesn't in really old browsers):
141-
```js run
142-
if (!window.Promise) {
143-
alert("Your browser is really old!");
144-
}
145-
```
77+
## Resumo
14678

147-
3. We can create "polyfills": add functions that are not supported by the environment (say, an old browser), but exist in the modern standard.
79+
- O objeto global contém variáveis que devem estar disponíveis em qualquer lugar.
14880

149-
```js run
150-
if (!window.Promise) {
151-
window.Promise = ... // custom implementation of the modern language feature
152-
}
153-
```
81+
Isso inclui objetos nativos Javascript, como `Array` e valores específicos do ambiente, como `window.innerHeight` -- a altura da janela no navegador.
82+
- O objeto global tem o nome universal `globalThis`.
15483

155-
...And of course, if we're in a browser, using `window` to access browser window features (not as a global object) is completely fine.
84+
...Porém é mais frequentemente referido pelos seu nomes específicos de ambientes "old-school", como `window` (navegador) e `global` (Node.js). Como `globalThis` é uma proposta recente, não é suportado pelo "non-Chromium Edge" (mas pode ser usado com um polyfill).
85+
- Devemos salvar valores no objeto global apenas se eles forem realmente globais em nosso projeto. E manter sua quantidade no mínimo.
86+
- No navegador, ao menos que estejamos usando [modules](info:modules), funções e variáveis globais declaradas com `var` tornam-se uma propriedade do objeto global.
87+
- Para tornar nosso código à prova de mudanças no futuro e mais fácil de entender, devemos acessar as propriedades do objeto global diretamente, como `window.x`.

0 commit comments

Comments
 (0)