This commit is contained in:
Ilya Kantor 2017-03-30 13:28:35 +03:00
parent bc9117e70f
commit 79f3775034
7 changed files with 89 additions and 75 deletions

View file

@ -233,6 +233,4 @@ Other symbols will also become familiar when we study the corresponding language
- Symbols created with `Symbol(name)` are always different, even if they have the same name. If we want same-named symbols to be equal, then we should use the global registry: `Symbol.for(name)` returns (creates if needed) a global symbol with the given name. Multiple calls return the same symbol.
- There are system symbols used by JavaScript and accessible as `Symbol.*`. We can use them to alter some built-in behaviors.
Technically, symbols are not 100% hidden. There is a build-in method [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols) that allows to get all symbols. Also there is a method named [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) that returns *all* keys of an object including symbolic ones. So they are not really hidden.
But most libraries, built-in methods and syntax constructs adhere to a common agreement that they are. And the one who explicitly calls the aforementioned methods probably understands well what he's doing.
Technically, symbols are not 100% hidden. There is a build-in method [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols) that allows to get all symbols. Also there is a method named [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) that returns *all* keys of an object including symbolic ones. So they are not really hidden. But most libraries, built-in methods and syntax constructs adhere to a common agreement that they are. And the one who explicitly calls the aforementioned methods probably understands well what he's doing.

View file

@ -9,9 +9,9 @@ let user = {
};
```
And, in the real world, a user can `act`: to select something from the shopping cart, to login, to logout etc.
And, in the real world, a user can *act*: select something from the shopping cart, login, logout etc.
Let's implement the same in JavaScript using functions in properties.
Actions are represented in JavaScript by functions in properties.
[cut]
@ -42,7 +42,7 @@ A function that is the property of an object is called its *method*.
So, here we've got a method `sayHi` of the object `user`.
Of course, we could use a Function Declaration to add a method:
Of course, we could use a pre-declared function as a method, like this:
```js run
let user = {
@ -55,19 +55,17 @@ function sayHi() {
alert("Hello!");
};
// then add the method
// then add as a method
user.sayHi = sayHi;
*/!*
user.sayHi(); // Hello!
```
That would also work, but is longer. Also we get an "extra" function `sayHi` outside of the `user` object. Usually we don't want that.
```smart header="Object-oriented programming"
When we write our code using objects to represent entities, that's called an [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming), in short: "OOP".
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.
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. We'll scratch the surface of that topic later in the chapter <info:object-oriented-programming>.
```
### Method shorthand
@ -100,7 +98,7 @@ To say the truth, the notations are not fully identical. There are subtle differ
It's common that an object method needs to access the information stored in the object to do its job.
For instance, `user.sayHi()` may need to mention the name of the user.
For instance, the code inside `user.sayHi()` may need the name of the `user`.
**To access the object, a method can use the `this` keyword.**
@ -115,7 +113,7 @@ let user = {
sayHi() {
*!*
alert( this.name ); // "this" means "this object"
alert(this.name);
*/!*
}
@ -126,14 +124,20 @@ user.sayHi(); // John
Here during the execution of `user.sayHi()`, the value of `this` will be `user`.
Technically, it's also possible to access the object without `this`:
Technically, it's also possible to access the object without `this`, by referencing it via the outer variable:
```js
...
let user = {
name: "John",
age: 30,
sayHi() {
alert( *!*user.name*/!* );
*!*
alert(user.name); // "user" instead of "this"
*/!*
}
...
};
```
...But such code is unreliable. If we decide to copy `user` to another variable, e.g. `admin = user` and overwrite `user` with something else, then it will access the wrong object.
@ -207,27 +211,29 @@ function sayHi() {
alert(this);
}
sayHi();
sayHi(); // undefined
```
In this case `this` is `undefined` in strict mode. If we try to access `this.name`, there will be an error.
In non-strict mode (if you forgot `use strict`) the value of `this` in such case will be the *global object* (`"window"` for browser, we'll study it later). This is just a historical thing that `"use strict"` fixes.
In non-strict mode (if one forgets `use strict`) the value of `this` in such case will be the *global object* (`window` in a browser, we'll get to it later). This is a historical behavior that `"use strict"` fixes.
Please note that usually a call of a function using `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.
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.
```smart header="The consequences of unbound `this`"
If you come from another programming languages, then you are probably used to an idea of a "bound `this`", where methods defined in an object always have `this` referencing that object.
The idea of unbound, run-time evaluated `this` has both pluses and minuses. From one side, a function can be reused for different objects. From the other side, greater flexibility opens a place for mistakes.
In JavaScript `this` is "free", its value is evaluated at the call time and depends not on where the method was declared, but rather on what's the object "before dot".
Here we are not to judge whether this language design decision is good or bad. We will understand how to work with it, how to get benefits and evade problems.
The concept of run-time evaluated `this` has both pluses and minuses. From one side, a function can be reused for different objects. From the other side, greater flexibility opens a place for mistakes.
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 evade problems.
```
## Internals: Reference Type
```warn header="In-depth language feature"
This section covers advanced topic that may interest those who want to know JavaScript better.
This section covers an advanced topic, to understand certain edge-cases better.
If you want to go on faster, it can be skipped or postponed.
```
@ -249,20 +255,32 @@ user.hi(); // John (the simple call works)
*/!*
```
On the last line there is an intricate code that evaluates an expression to get the method. In this case the result is `user.hi`.
On the last line there is a ternary operator that chooses either `user.hi` or `user.bye`. In this case the result is `user.hi`.
The method is immediately called with brackets `()`. But that doesn't work right. You can see that the call results in an error, cause the value of `"this"` inside the call becomes `undefined`.
The method is immediately called with parentheses `()`. But it doesn't work right!
Actually, anything more complex than a simple `obj.method()` (or square brackets here) looses `this`.
You can see that the call results in an error, cause the value of `"this"` inside the call becomes `undefined`.
If we want to understand why it happens -- let's get under the hood of how `obj.method()` call works.
This works (object dot method):
```js
user.hi();
```
This doesn't (evaluated method):
```js
(user.name == "John" ? user.hi : user.bye)(); // Error!
```
Why? If we want to understand why it happens -- let's get under the hood of how `obj.method()` call works.
Looking closely, we may notice two operations in `obj.method()` statement:
- the dot `'.'` retrieves the property `obj.method`.
- brackets `()` execute it (assuming that's a function).
1. First, the dot `'.'` retrieves the property `obj.method`.
2. Then parentheses `()` execute it.
So, you might have already asked yourself, why does it work? That is, if we put these operations on separate lines, then `this` will be lost for sure:
So, how the information about `this` gets passed from the first part to the second one?
If we put these operations on separate lines, then `this` will be lost for sure:
```js run
let user = {
@ -277,7 +295,7 @@ hi(); // Error, because this is undefined
*/!*
```
That's because a function is a value of its own. It does not carry the object. So `hi = user.hi` saves it into the variable, and then on the last line it is completely standalone.
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`.
**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).**
@ -289,14 +307,14 @@ The value of Reference Type is a three-value combination `(base, name, strict)`,
- `name` is the property.
- `strict` is true if `use strict` is in effect.
The result of a property access `'.'` is a value of Reference Type. For `user.hi` in strict mode it is:
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:
```js
// Reference Type value
(user, "hi", true)
```
When brackets `()` are called on the Reference Type, they receive the full information about the object and it's method, and can set the right `this` (`=user` in this case).
When parentheses `()` are called on the Reference Type, they receive the full information about the object and it's method, and can set the right `this` (`=user` in this case).
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 "looses" `this`.
@ -320,7 +338,7 @@ let user = {
user.sayHi(); // Ilya
```
That's a special feature of arrow functions, it's useful when we actually do not want to have a separate `this`, but rather to take it from the outer context. Later in the chapter <info:arrow-functions> we'll dig more deeply into what's going on.
That's a special feature of arrow functions, it's useful when we actually do not want to have a separate `this`, but rather to take it from the outer context. Later in the chapter <info:arrow-functions> we'll go more deeply into arrow functions.
## Summary

View file

@ -1,41 +1,32 @@
# Object to primitive conversion
In the chapter <info:type-conversions> we've seen the rules for numeric, string and boolean conversions of primitives.
What happens when objects are added `obj1 + obj2`, substracted `obj1 - obj2` or printed using `alert(obj)`?
But we left a gap for objects. Now let's close it. And, in the process, we'll see some built-in methods and the example of a built-in symbol.
There are special methods in objects that do the conversion.
In the chapter <info:type-conversions> we've seen the rules for numeric, string and boolean conversions of primitives. But we left a gap for objects. Now, as we know about methods and symbols it becomes possible to close it.
[cut]
## Where and why?
The process of object to primitive conversion can be customized, here we'll see how to implement our own methods for it. But first, let's see when it happens.
That's because the conversion of an object to primitive value (a number or a string) is a rare thing in practice.
For objects, there's no to-boolean conversion, because all objects are `true` in a boolean context. So there are only string and numeric conversions.
For instance, numeric conversion happens in most mathematical functions. But do we run maths on an object as a whole? Rarely the case. It also occurs when we compare an object against a primitive: `user > 18`. But should we write like that? What such comparison actually means? Maybe we want to compare `18` against the age of the `user`? Then it would be more obvious to write `user.age > 18`. And it's easier to read and understand it too.
The numeric conversion happens when we substract objects or apply mathematical functions. For instance, `Date` objects (to be covered in the chapter <info:date>) can be substracted, and the result of `date1 - date2` is the time difference between two dates.
As for the string conversion... Where does it occur? Usually, when we output an object like `alert(obj)`. But `alert` and similar ways to show an object are only used for debugging and logging purposes. For real stuff, the output is more complicated. It is usually implemented with special object methods like `user.format(...)` or in more advanced ways.
Still, there are still valid reasons why we should know how to-primitive conversion works:
- Simple object-as-string output (`alert` and alike) is useable sometimes.
- Many built-in objects implement their own to-primitive conversion, we need to know how to work with that.
- Sometimes an unexpected conversion happens, and we should understand what's going on.
- The final one. There are quizzes and questions on interviews that rely on that knowledge. Looks like people think it's a good sign that person understands JavaScript if he knows type conversions well.
As for the string conversion -- it usually happens when we output an object like `alert(obj)` and in similar contexts.
## ToPrimitive
When an object is used in the context where a primitive is required, it is converted to primitive using the `ToPrimitive` algorithm, thoroughly described in the [specification](https://tc39.github.io/ecma262/#sec-toprimitive)).
When an object is used in the context where a primitive is required, for instance, in an `alert` or mathematical operations, it's converted to a primitive value using the `ToPrimitive` algorithm ([specification](https://tc39.github.io/ecma262/#sec-toprimitive)).
That algorithm joins all conversion cases and allows to customize them in a special object method.
That algorithm allows to customize the conversion using in a special object method.
When a built-in function (like `alert` or mathematical functions) or an operator (like an addition or substraction) get an object as their argument, they initiate the to-primitive conversion using one of 3 so-called "hints":
Depending on the context, the conversion has a so-called "hint".
There are 3 variants:
`"string"`
: When an operation expects a string, for object-to-string conversions, like:
: When an operation expects a string, for object-to-string conversions, like `alert`:
```js
// output
@ -46,7 +37,7 @@ When a built-in function (like `alert` or mathematical functions) or an operator
```
`"number"`
: When an operation expects a number, for object-to-number conversions, like:
: When an operation expects a number, for object-to-number conversions, like maths:
```js
// explicit conversion
@ -63,9 +54,7 @@ When a built-in function (like `alert` or mathematical functions) or an operator
`"default"`
: Occurs in rare cases when the operator is "not sure" what type to expect.
For instance, binary plus `+` can work both with strings (concatenates them) and numbers (adds them).
Or when an object is compared with a string, number or a symbol using `==`, then also the `"default"` hint is used.
For instance, binary plus `+` can work both with strings (concatenates them) and numbers (adds them), so both strings and numbers would do. Or when an object is compared using `==` with a string, number or a symbol.
```js
// binary plus
@ -75,7 +64,7 @@ When a built-in function (like `alert` or mathematical functions) or an operator
if (user == 1) { ... };
```
Seems right to use that hint for binary addition `+` and equality check `==`, because they operate both on strings and numbers. Although, there's some inconsistency here. The greater/less operator `<>` can work with both strings and numbers too. Still, it uses "number" hint, not "default". That's for historical reasons.
The greater/less operator `<>` can work with both strings and numbers too. Still, it uses "number" hint, not "default". That's for historical reasons.
In practice, all built-in objects except for one case (`Date` object, we'll learn it later) implement `"default"` conversion the same way as `"number"`. And probably we should do the same.
@ -185,11 +174,11 @@ An operation that initiated the conversion gets that primitive, and then continu
For instance:
- Mathematical operations (except binary plus) apply `ToNumber` after `ToPrimitive` with `"number"` hint:
- Mathematical operations (except binary plus) perform `ToNumber` conversion:
```js run
let obj = {
toString() { // toString handles all ToPrimitive in the absense of other methods
toString() { // toString handles all conversions in the absense of other methods
return "2";
}
};
@ -197,7 +186,7 @@ For instance:
alert(obj * 2); // 4, ToPrimitive gives "2", then it becomes 2
```
- Binary plus first checks if the primitive is a string, and then does concatenation, otherwise performs `ToNumber` and works with numbers.
- Binary plus performs checks the primitive -- if it's a string, then it does concatenation, otherwise performs `ToNumber` and works with numbers.
String example:
```js run
@ -221,9 +210,10 @@ For instance:
alert(obj + 2); // 3 (ToPrimitive returned boolean, not string => ToNumber)
```
```smart header="Minor notes"
- If `Symbol.toPrimitive` exists, it *must* return an primitive, otherwise there will be an error.
- Methods `toString` or `valueOf` *should* return a primitive: if any of them returns and object, then it is ignored (like if the method didn't exist). That's the historical behavior.
```smart header="Historical notes"
For historical reasons, methods `toString` or `valueOf` *should* return a primitive: if any of them returns an object, then there's no error, but the object is ignored (like if the method didn't exist).
In contrast, `Symbol.toPrimitive` *must* return an primitive, otherwise there will be an error.
```
## Summary
@ -231,11 +221,11 @@ For instance:
The object-to-primitive conversion is called automatically by many built-in functions and operators that expect a primitive as a value.
There are 3 types (hints) of it:
- `"string"`
- `"number"`
- `"default"`
- `"string"` (for `alert` and other string conversions)
- `"number"` (for maths)
- `"default"` (few operators)
So, operations use the hint depending on what they expect to get. The specification describes explicitly which operator uses which hint. There are very few operators that "don't know what to expect" and use the `"default"` hint. Usually for built-in objects it works the same way as `"number"`, so in practice the last two are often merged together.
The specification describes explicitly which operator uses which hint. There are very few operators that "don't know what to expect" and use the `"default"` hint. Usually for built-in objects `"default"` hint is handled the same way as `"number"`, so in practice the last two are often merged together.
The conversion algorithm is:

View file

@ -2,7 +2,7 @@ importance: 2
---
# Two functions -- one object
# Two functions one object
Is it possible to create functions `A` and `B` such as `new A()==new B()`?

View file

@ -1,4 +1,4 @@
# Constructor, operator "new"
# Constructor, operator "new"
The regular `{...}` syntax allows to create one object. But often we need to create many similar objects.
@ -210,4 +210,10 @@ john = {
We can use constructor functions to make multiple similar objects. But the topic is much deeper than described here. So we'll return it later and cover more in-depth.
As of now, it's important to understand what `new` is, because JavaScript provides constructor functions for many built-in language objects: like `Date` for dates, `Set` for sets and others that we plan to study.
JavaScript provides constructor functions for many built-in language objects: like `Date` for dates, `Set` for sets and others that we plan to study.
```smart header="Objects, we'll be back!"
In this chapter we only cover the basics about objects. They are essential for learning more about data types and functions in the next chapters.
After the learn that, in the chapter <info:object-oriented-programming> we return to objects and cover them in-depth, including inheritance and classes.
```