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/02-first-steps/18-javascript-specials/article.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -144,7 +144,7 @@ Assignments
144
144
: There is a simple assignment: `a = b` and combined ones like `a *= 2`.
145
145
146
146
Bitwise
147
-
: Bitwise operators work with 32-bit integers at the lowest, bit-level: see the [docs](mdn:/JavaScript/Reference/Operators/Bitwise_Operators) when they are needed.
147
+
: Bitwise operators work with 32-bit integers at the lowest, bit-level: see the [docs](mdn:/JavaScript/Guide/Expressions_and_Operators#Bitwise) when they are needed.
148
148
149
149
Conditional
150
150
: The only operator with three parameters: `cond ? resultA : resultB`. If `cond` is truthy, returns `resultA`, otherwise `resultB`.
Copy file name to clipboardExpand all lines: 1-js/04-object-basics/02-object-copy/article.md
+27-19Lines changed: 27 additions & 19 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,12 @@
1
-
# Object copying, references
1
+
# Object references and copying
2
2
3
-
One of the fundamental differences of objects vs primitives is that they are stored and copied "by reference".
3
+
One of the fundamental differences of objects versus primitives is that objects are stored and copied "by reference", as opposed to primitive values: strings, numbers, booleans, etc -- that are always copied "as a whole value".
4
4
5
-
Primitive values: strings, numbers, booleans -- are assigned/copied "as a whole value".
5
+
That's easy to understand if we look a bit "under a cover" of what happens when we copy a value.
6
6
7
-
For instance:
7
+
Let's start with a primitive, such as a string.
8
+
9
+
Here we put a copy of `message` into `phrase`:
8
10
9
11
```js
10
12
let message ="Hello!";
@@ -15,21 +17,31 @@ As a result we have two independent variables, each one is storing the string `"
15
17
16
18

17
19
20
+
Quite an obvious result, right?
21
+
18
22
Objects are not like that.
19
23
20
-
**A variable stores not the object itself, but its "address in memory", in other words "a reference" to it.**
24
+
**A variable assigned to an object stores not the object itself, but its "address in memory", in other words "a reference" to it.**
21
25
22
-
Here's the picture for the object:
26
+
Let's look at an example of such variable:
23
27
24
28
```js
25
29
let user = {
26
30
name:"John"
27
31
};
28
32
```
29
33
34
+
And here's how it's actually stored in memory:
35
+
30
36

31
37
32
-
Here, the object is stored somewhere in memory. And the variable `user` has a "reference" to it.
38
+
The object is stored somewhere in memory (at the right of the picture), while the `user` variable (at the left) has a "reference" to it.
39
+
40
+
We may think of an object variable, such as `user`, as of a sheet of paper with the address.
41
+
42
+
When we perform actions with the object, e.g. take a property `user.name`, JavaScript engine looks into that address and performs the operation on the actual object.
43
+
44
+
Now here's why it's important.
33
45
34
46
**When an object variable is copied -- the reference is copied, the object is not duplicated.**
35
47
@@ -45,6 +57,8 @@ Now we have two variables, each one with the reference to the same object:
45
57
46
58

47
59
60
+
As you can see, there's still one object, now with two variables that reference it.
61
+
48
62
We can use any variable to access the object and modify its contents:
49
63
50
64
```js run
@@ -59,15 +73,14 @@ admin.name = 'Pete'; // changed by the "admin" reference
59
73
alert(*!*user.name*/!*); //'Pete', changes are seen from the "user" reference
60
74
```
61
75
62
-
The example above demonstrates that there is only one object. As if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use another key (`user`) we can see changes.
63
76
64
-
## Comparison by reference
77
+
It's just as if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use another key (`user`) we can see changes.
65
78
66
-
The equality `==` and strict equality `===` operators for objects work exactly the same.
79
+
## Comparison by reference
67
80
68
-
**Two objects are equal only if they are the same object.**
81
+
Two objects are equal only if they are the same object.
69
82
70
-
Here two variables reference the same object, thus they are equal:
83
+
For instance, here `a` and `b` reference the same object, thus they are equal:
71
84
72
85
```js run
73
86
let a = {};
@@ -77,7 +90,7 @@ alert( a == b ); // true, both variables reference the same object
77
90
alert( a === b ); // true
78
91
```
79
92
80
-
And here two independent objects are not equal, even though both are empty:
93
+
And here two independent objects are not equal, even though they look alike (both are empty):
81
94
82
95
```js run
83
96
let a = {};
@@ -86,7 +99,7 @@ let b = {}; // two independent objects
86
99
alert( a == b ); // false
87
100
```
88
101
89
-
For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj ==5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons occur very rarely, usually as a result of a coding mistake.
102
+
For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj ==5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons are needed very rarely, usually they appear as a result of a programming mistake.
90
103
91
104
## Cloning and merging, Object.assign
92
105
@@ -215,11 +228,6 @@ alert(clone.sizes.width); // 51, see the result from the other one
215
228
216
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".
217
230
218
-
<<<<<<< HEAD
219
-
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).
220
-
221
-
=======
222
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
223
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 = {
@@ -32,11 +32,11 @@ user.sayHi = function() {
32
32
user.sayHi(); // Hello!
33
33
```
34
34
35
-
Here we've just used a Function Expression to create the function and assign it to the property `user.sayHi` of the object.
35
+
Here we've just used a Function Expression to create a function and assign it to the property `user.sayHi` of the object.
36
36
37
-
Then we can call it. The user can now speak!
37
+
Then we can call it as `user.sayHi()`. The user can now speak!
38
38
39
-
A function that is the property of an object is called its *method*.
39
+
A function that is a property of an object is called its *method*.
40
40
41
41
So, here we've got a method `sayHi` of the object `user`.
42
42
@@ -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
}
@@ -163,18 +160,16 @@ let user = {
163
160
let admin = user;
164
161
user =null; // overwrite to make things obvious
165
162
166
-
admin.sayHi(); // Whoops! inside sayHi(), the old name is used! error!
163
+
*!*
164
+
admin.sayHi(); // TypeError: Cannot read property 'name' of null
165
+
*/!*
167
166
```
168
167
169
168
If we used `this.name` instead of `user.name` inside the `alert`, then the code would work.
170
169
171
170
## "this" is not bound
172
171
173
-
<<<<<<< HEAD
174
-
In JavaScript, "this" keyword behaves unlike most other programming languages. First, it can be used in any function.
175
-
=======
176
-
In JavaScript, keyword `this` behaves unlike most other programming languages. It can be used in any function.
177
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
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.
178
173
179
174
There's no syntax error in the following example:
180
175
@@ -184,9 +179,9 @@ function sayHi() {
184
179
}
185
180
```
186
181
187
-
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.
188
183
189
-
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)
211
206
```
212
207
213
-
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:
214
212
215
213
```js run
216
214
functionsayHi() {
@@ -224,12 +222,8 @@ In this case `this` is `undefined` in strict mode. If we try to access `this.nam
224
222
225
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.
226
224
227
-
<<<<<<< HEAD
228
-
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.
229
-
=======
230
225
Usually such call is a programming error. If there's `this` inside a function, it expects to be called in an object context.
231
226
````
232
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
233
227
234
228
```smart header="The consequences of unbound `this`"
235
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.
@@ -241,99 +235,6 @@ The concept of run-time evaluated `this` has both pluses and minuses. On the one
241
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.
242
236
```
243
237
244
-
<<<<<<< HEAD
245
-
## Internals: Reference Type
246
-
247
-
```warn header="In-depth language feature"
248
-
This section covers an advanced topic, to understand certain edge-cases better.
249
-
250
-
If you want to go on faster, it can be skipped or postponed.
251
-
```
252
-
253
-
An intricate method call can lose `this`, for instance:
254
-
255
-
```js run
256
-
let user = {
257
-
name: "John",
258
-
hi() { alert(this.name); },
259
-
bye() { alert("Bye"); }
260
-
};
261
-
262
-
user.hi(); // John (the simple call works)
263
-
264
-
*!*
265
-
// 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.
287
-
288
-
Looking closely, we may notice two operations in `obj.method()` statement:
289
-
290
-
1. First, the dot `'.'` retrieves the property `obj.method`.
291
-
2. Then parentheses `()` execute it.
292
-
293
-
So, how does the information about `this` get passed from the first part to the second one?
294
-
295
-
If we put these operations on separate lines, then `this` will be lost for sure:
296
-
297
-
```js run
298
-
let user = {
299
-
name: "John",
300
-
hi() { alert(this.name); }
301
-
}
302
-
303
-
*!*
304
-
// split getting and calling the method in two lines
305
-
let hi = user.hi;
306
-
hi(); // Error, because this is undefined
307
-
*/!*
308
-
```
309
-
310
-
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`.
311
-
312
-
**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).**
313
-
314
-
The Reference Type is a "specification type". We can't explicitly use it, but it is used internally by the language.
315
-
316
-
The value of Reference Type is a three-value combination `(base, name, strict)`, where:
317
-
318
-
- `base` is the object.
319
-
- `name` is the property.
320
-
- `strict` is true if `use strict` is in effect.
321
-
322
-
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:
323
-
324
-
```js
325
-
// Reference Type value
326
-
(user, "hi", true)
327
-
```
328
-
329
-
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).
330
-
331
-
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`.
332
-
333
-
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).
334
-
335
-
=======
336
-
>>>>>>> e074a5f825a3d10b0c1e5e82561162f75516d7e3
337
238
## Arrow functions have no "this"
338
239
339
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.
@@ -363,7 +264,7 @@ That's a special feature of arrow functions, it's useful when we actually do not
363
264
364
265
The value of `this` is defined at run-time.
365
266
- When a function is declared, it may use `this`, but that `this` has no value until the function is called.
366
-
- That function can be copied between objects.
267
+
- A function can be copied between objects.
367
268
- When a function is called in the "method" syntax: `object.method()`, the value of `this` during the call is `object`.
368
269
369
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.
0 commit comments