You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/01-getting-started/1-intro/article.md
-15Lines changed: 0 additions & 15 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,6 @@
1
1
# Uma Introdução ao JavaScript
2
2
3
-
<<<<<<< HEAD
4
3
Vamos ver o que há de tão especial no JavaScript, o que podemos fazer com ele, e que outras tecnologias funcionam bem com ele.
5
-
=======
6
-
Let's see what's so special about JavaScript, what we can achieve with it, and what other technologies play well with it.
7
-
>>>>>>> 0599d07b3c13ee25f583fc091cead3c17a7e7779
8
4
9
5
## O que é JavaScript?
10
6
@@ -71,13 +67,8 @@ Exemplos de tais restrições incluem:
71
67
72
68
Os navegadores modernos permitem que ele trabalhe com arquivos, mas o acesso é limitado e fornecido apenas se o usuário executar determinadas ações, como "dropping" de um arquivo em uma janela do navegador ou selecioná-lo por meio de uma tag `<input>`.
73
69
74
-
<<<<<<< HEAD
75
70
Existem maneiras de interagir com a câmera / microfone e outros dispositivos, mas eles exigem permissão explícita do usuário. Assim, uma página habilitada para JavaScript pode não habilmente habilitar uma câmera web, observar os arredores e enviar as informações para a [NSA](https://pt.wikipedia.org/wiki/Ag%C3%AAncia_de_Seguran%C3%A7a_Nacional).
76
71
- Diferentes abas/janelas geralmente não se conhecem mutuamente. Às vezes sim, por exemplo, quando uma janela usa JavaScript para abrir a outra. Mas mesmo neste caso, JavaScript de uma página pode não acessar a outra se eles vierem de sites diferentes (de um domínio, protocolo ou porta diferente).
77
-
=======
78
-
There are ways to interact with camera/microphone and other devices, but they require a user's explicit permission. So a JavaScript-enabled page may not sneakily enable a web-camera, observe the surroundings and send the information to the [NSA](https://en.wikipedia.org/wiki/National_Security_Agency).
79
-
- Different tabs/windows generally do not know about each other. Sometimes they do; for example when one window uses JavaScript to open the other one. But even in this case, JavaScript from one page may not access the other if they come from different sites (from a different domain, protocol or port).
80
-
>>>>>>> 0599d07b3c13ee25f583fc091cead3c17a7e7779
81
72
82
73
Isso é chamado de "Política de mesma origem ". Para contornar isso, *ambas as páginas* devem conter um código JavaScript especial que lida com a troca de dados.
83
74
@@ -125,12 +116,6 @@ Há mais. Claro que, mesmo que usemos uma dessas linguagens transpiladas, també
125
116
126
117
## Resumo
127
118
128
-
<<<<<<< HEAD
129
119
- O JavaScript foi inicialmente criado como uma linguagem somente de navegador, mas agora é usado em muitos outros ambientes também.
130
120
- Hoje, o JavaScript tem uma posição única como a linguagem de navegador mais amplamente adotada, com integração total com HTML/CSS.
131
121
- Existem muitas linguagens que são "transpiladas" para JavaScript e que oferecem certas funcionalidades. Recomenda-se dar uma olhada nelas, pelo menos brevemente, depois de dominar o JavaScript.
132
-
=======
133
-
- JavaScript was initially created as a browser-only language, but it is now used in many other environments as well.
134
-
- Today, JavaScript has a unique position as the most widely-adopted browser language with full integration in HTML/CSS.
135
-
- There are many languages that get "transpiled" to JavaScript and provide certain features. It is recommended to take a look at them, at least briefly, after mastering JavaScript.
Copy file name to clipboardExpand all lines: 1-js/04-object-basics/02-object-copy/article.md
-5Lines changed: 0 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -228,11 +228,6 @@ alert(clone.sizes.width); // 51, see the result from the other one
228
228
229
229
To fix that, we should use the cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning".
230
230
231
-
<<<<<<< HEAD
232
-
There's a standard algorithm for deep cloning that handles the case above and more complex cases, called the [Structured cloning algorithm](https://html.spec.whatwg.org/multipage/structured-data.html#safe-passing-of-structured-data).
233
-
234
-
=======
235
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
236
231
We can use recursion to implement it. Or, not to reinvent the wheel, take an existing implementation, for instance [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) from the JavaScript library [lodash](https://lodash.com).
@@ -15,7 +15,7 @@ Actions are represented in JavaScript by functions in properties.
15
15
16
16
## Method examples
17
17
18
-
For the start, let's teach the `user` to say hello:
18
+
For a start, let's teach the `user` to say hello:
19
19
20
20
```js run
21
21
let user = {
@@ -63,11 +63,7 @@ user.sayHi(); // Hello!
63
63
```smart header="Object-oriented programming"
64
64
When we write our code using objects to represent entities, that's called [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming), in short: "OOP".
65
65
66
-
<<<<<<< HEAD
67
-
OOP is a big thing, an interesting science of its own. How to choose the right entities? How to organize the interaction between them? That's architecture, and there are great books on that topic, like "Design Patterns: Elements of Reusable Object-Oriented Software" by E.Gamma, R.Helm, R.Johnson, J.Vissides or "Object-Oriented Analysis and Design with Applications" by G.Booch, and more.
68
-
=======
69
66
OOP is a big thing, an interesting science of its own. How to choose the right entities? How to organize the interaction between them? That's architecture, and there are great books on that topic, like "Design Patterns: Elements of Reusable Object-Oriented Software" by E. Gamma, R. Helm, R. Johnson, J. Vissides or "Object-Oriented Analysis and Design with Applications" by G. Booch, and more.
70
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
71
67
```
72
68
### Method shorthand
73
69
@@ -76,14 +72,14 @@ There exists a shorter syntax for methods in an object literal:
76
72
```js
77
73
// these objects do the same
78
74
79
-
letuser = {
75
+
user = {
80
76
sayHi:function() {
81
77
alert("Hello");
82
78
}
83
79
};
84
80
85
81
// method shorthand looks better, right?
86
-
letuser = {
82
+
user = {
87
83
*!*
88
84
sayHi() { // same as "sayHi: function()"
89
85
*/!*
@@ -115,6 +111,7 @@ let user = {
115
111
116
112
sayHi() {
117
113
*!*
114
+
// "this" is the "current object"
118
115
alert(this.name);
119
116
*/!*
120
117
}
@@ -172,15 +169,7 @@ If we used `this.name` instead of `user.name` inside the `alert`, then the code
172
169
173
170
## "this" is not bound
174
171
175
-
<<<<<<< HEAD
176
-
<<<<<<< HEAD
177
-
In JavaScript, "this" keyword behaves unlike most other programming languages. First, it can be used in any function.
178
-
=======
179
-
In JavaScript, keyword `this` behaves unlike most other programming languages. It can be used in any function.
180
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
181
-
=======
182
172
In JavaScript, keyword `this` behaves unlike most other programming languages. It can be used in any function, even if it's not a method of an object.
183
-
>>>>>>> 0599d07b3c13ee25f583fc091cead3c17a7e7779
184
173
185
174
There's no syntax error in the following example:
186
175
@@ -190,9 +179,9 @@ function sayHi() {
190
179
}
191
180
```
192
181
193
-
The value of `this` is evaluated during the run-time. And it can be anything.
182
+
The value of `this` is evaluated during the run-time, depending on the context.
194
183
195
-
For instance, the same function may have different "this" when called from different objects:
184
+
For instance, here the same function is assigned to two different objects and has different "this" in the calls:
admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)
217
206
```
218
207
219
-
Actually, we can call the function without an object at all:
208
+
The rule is simple: if `obj.f()` is called, then `this` is `obj` during the call of `f`. So it's either `user` or `admin` in the example above.
209
+
210
+
````smart header="Calling without an object: `this == undefined`"
211
+
We can even call the function without an object at all:
220
212
221
213
```js run
222
214
functionsayHi() {
@@ -230,12 +222,8 @@ In this case `this` is `undefined` in strict mode. If we try to access `this.nam
230
222
231
223
In non-strict mode the value of `this` in such case will be the *global object* (`window` in a browser, we'll get to it later in the chapter [](info:global-object)). This is a historical behavior that `"use strict"` fixes.
232
224
233
-
<<<<<<< HEAD
234
-
Please note that usually a call of a function that uses `this` without an object is not normal, but rather a programming mistake. If a function has `this`, then it is usually meant to be called in the context of an object.
235
-
=======
236
225
Usually such call is a programming error. If there's `this` inside a function, it expects to be called in an object context.
237
226
````
238
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
239
227
240
228
```smart header="The consequences of unbound `this`"
241
229
If you come from another programming language, then you are probably used to the idea of a "bound `this`", where methods defined in an object always have `this` referencing that object.
@@ -247,99 +235,6 @@ The concept of run-time evaluated `this` has both pluses and minuses. On the one
247
235
Here our position is not to judge whether this language design decision is good or bad. We'll understand how to work with it, how to get benefits and avoid problems.
248
236
```
249
237
250
-
<<<<<<< HEAD
251
-
## Internals: Reference Type
252
-
253
-
```warn header="In-depth language feature"
254
-
This section covers an advanced topic, to understand certain edge-cases better.
255
-
256
-
If you want to go on faster, it can be skipped or postponed.
257
-
```
258
-
259
-
An intricate method call can lose `this`, for instance:
260
-
261
-
```js run
262
-
let user = {
263
-
name: "John",
264
-
hi() { alert(this.name); },
265
-
bye() { alert("Bye"); }
266
-
};
267
-
268
-
user.hi(); // John (the simple call works)
269
-
270
-
*!*
271
-
// now let's call user.hi or user.bye depending on the name
Why? If we want to understand why it happens, let's get under the hood of how `obj.method()` call works.
293
-
294
-
Looking closely, we may notice two operations in `obj.method()` statement:
295
-
296
-
1. First, the dot `'.'` retrieves the property `obj.method`.
297
-
2. Then parentheses `()` execute it.
298
-
299
-
So, how does the information about `this` get passed from the first part to the second one?
300
-
301
-
If we put these operations on separate lines, then `this` will be lost for sure:
302
-
303
-
```js run
304
-
let user = {
305
-
name: "John",
306
-
hi() { alert(this.name); }
307
-
}
308
-
309
-
*!*
310
-
// split getting and calling the method in two lines
311
-
let hi = user.hi;
312
-
hi(); // Error, because this is undefined
313
-
*/!*
314
-
```
315
-
316
-
Here `hi = user.hi` puts the function into the variable, and then on the last line it is completely standalone, and so there's no `this`.
317
-
318
-
**To make `user.hi()` calls work, JavaScript uses a trick -- the dot `'.'` returns not a function, but a value of the special [Reference Type](https://tc39.github.io/ecma262/#sec-reference-specification-type).**
319
-
320
-
The Reference Type is a "specification type". We can't explicitly use it, but it is used internally by the language.
321
-
322
-
The value of Reference Type is a three-value combination `(base, name, strict)`, where:
323
-
324
-
- `base` is the object.
325
-
- `name` is the property.
326
-
- `strict` is true if `use strict` is in effect.
327
-
328
-
The result of a property access `user.hi` is not a function, but a value of Reference Type. For `user.hi` in strict mode it is:
329
-
330
-
```js
331
-
// Reference Type value
332
-
(user, "hi", true)
333
-
```
334
-
335
-
When parentheses `()` are called on the Reference Type, they receive the full information about the object and its method, and can set the right `this` (`=user` in this case).
336
-
337
-
Any other operation like assignment `hi = user.hi` discards the reference type as a whole, takes the value of `user.hi` (a function) and passes it on. So any further operation "loses" `this`.
338
-
339
-
So, as the result, the value of `this` is only passed the right way if the function is called directly using a dot `obj.method()` or square brackets `obj['method']()` syntax (they do the same here). Later in this tutorial, we will learn various ways to solve this problem such as [func.bind()](/bind#solution-2-bind).
340
-
341
-
=======
342
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
343
238
## Arrow functions have no "this"
344
239
345
240
Arrow functions are special: they don't have their "own" `this`. If we reference `this` from such a function, it's taken from the outer "normal" function.
@@ -369,7 +264,7 @@ That's a special feature of arrow functions, it's useful when we actually do not
369
264
370
265
The value of `this` is defined at run-time.
371
266
- When a function is declared, it may use `this`, but that `this` has no value until the function is called.
372
-
- That function can be copied between objects.
267
+
- A function can be copied between objects.
373
268
- When a function is called in the "method" syntax: `object.method()`, the value of `this` during the call is `object`.
374
269
375
270
Please note that arrow functions are special: they have no `this`. When `this` is accessed inside an arrow function, it is taken from outside.
Please note: the `?.` syntax works exactly where it's placed, not any further.
75
-
76
-
In the last two lines the evaluation stops immediately after `user?.`, never accessing further properties. But if the `user` actually exists, then the further intermediate properties, such as `user.address` must exist.
77
-
=======
78
63
alert( user?.address.street ); // undefined
79
64
```
80
65
@@ -83,7 +68,6 @@ Please note: the `?.` syntax makes optional the value before it, but not any fur
83
68
In the example above, `user?.` allows only `user` to be `null/undefined`.
84
69
85
70
On the other hand, if `user` does exist, then it must have `user.address` property, otherwise `user?.address.street` gives an error at the second dot.
86
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
87
71
88
72
```warn header="Don't overuse the optional chaining"
89
73
We should use `?.` only where it's ok that something doesn't exist.
@@ -93,27 +77,14 @@ For example, if according to our coding logic `user` object must be there, but `
93
77
So, if`user` happens to be undefined due to a mistake, we'll see a programming error about it and fix it. Otherwise, coding errors can be silenced where not appropriate, and become more difficult to debug.
94
78
```
95
79
96
-
<<<<<<<HEAD
97
-
````warn header="The variable before `?.` must exist"
98
-
If there's no variable `user`, then `user?.anything` triggers an error:
99
-
=======
100
80
````warn header="The variable before `?.` must be declared"
101
81
If there's no variable `user` at all, then `user?.anything` triggers an error:
102
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
103
82
104
83
```js run
105
84
// ReferenceError: user is not defined
106
85
user?.address;
107
86
```
108
-
<<<<<<<HEAD
109
-
<<<<<<<HEAD
110
-
The optional chaining only tests for`null/undefined`, doesn't interfere with any other language mechanics.
111
-
=======
112
-
There must be `let/const/var user`. The optional chaining works only for declared variables.
113
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
114
-
=======
115
87
There must be a declaration (e.g. `let/const/var user`). The optional chaining works only for declared variables.
116
-
>>>>>>> 0599d07b3c13ee25f583fc091cead3c17a7e7779
117
88
````
118
89
119
90
## Short-circuiting
@@ -158,15 +129,7 @@ user2.admin?.();
158
129
159
130
Here, in both lines we first use the dot (`user1.admin`) to get `admin` property, because the user object must exist, so it's safe read from it.
160
131
161
-
<<<<<<< HEAD
162
-
<<<<<<< HEAD
163
-
Then `?.()` checks the left part: if the user exists, then it runs (for `user1`). Otherwise (for `user2`) the evaluation stops without errors.
164
-
=======
165
-
Then `?.()` checks the left part: if the admin function exists, then it runs (for `user1`). Otherwise (for `user2`) the evaluation stops without errors.
166
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
167
-
=======
168
132
Then `?.()` checks the left part: if the admin function exists, then it runs (that's so for `user1`). Otherwise (for `user2`) the evaluation stops without errors.
169
-
>>>>>>> 0599d07b3c13ee25f583fc091cead3c17a7e7779
170
133
171
134
The `?.[]` syntax also works, if we'd like to use brackets `[]` to access properties instead of dot `.`. Similar to previous cases, it allows to safely read a property from an object that may not exist.
0 commit comments