Finished Chapter 6.9 Object Methods
parent
ea7d183da6
commit
574b235324
|
@ -462,14 +462,78 @@ What can/cannot be serialized?
|
|||
|
||||
## 6.9 Object Methods
|
||||
|
||||
All JS objects (excpet explicitly created w/o prototype) inherits properties from `Object.prototype`. Hence they inherited some **primarily methods**, which are universally available.
|
||||
* `hasOwnProperty()`, `propertyIsEnumerable()`
|
||||
* `Object.create()`, `Object.keys()`
|
||||
* `toString`
|
||||
* ...
|
||||
|
||||
### 6.9.1 The toString() Method
|
||||
|
||||
* `toString()` takes no arg, and returns a string that represents the value of obj.
|
||||
* Default `toString()` is not useful (e.g. shown below), each class define their own `toString()`
|
||||
|
||||
```js
|
||||
let s = { x: 1, y: 1 }.toString(); // s evaluate to "[object Object]", without show real information
|
||||
```
|
||||
|
||||
* We can redefine `toString()` method:
|
||||
|
||||
```js
|
||||
let point = {
|
||||
x: 1,
|
||||
y: 2,
|
||||
toString: function() { return `(${this.x}, ${this.y})`; }
|
||||
};
|
||||
|
||||
String(point) // => "(1, 2)": toString() is used for string conversions
|
||||
```
|
||||
|
||||
### 6.9.2 The toLocaleString() Method
|
||||
|
||||
`toLocaleString()`:
|
||||
* All objs have this method
|
||||
* Purpose of this method: return a localized (vs. internationalization) string representation of the obj.
|
||||
* default `toLocaleString()` defined by Object call `toString()` directly
|
||||
* Date/Number class defin customized versions of `toLocaleString()` to format date, currency, time, etc.
|
||||
* User can create their own method:
|
||||
|
||||
```js
|
||||
let point = {
|
||||
x: 1000,
|
||||
y: 2000,
|
||||
toString: function() { return `(${this.x}, ${this.y})`; },
|
||||
toLocaleString: function() {
|
||||
return `(${this.x.toLocaleString()}, ${this.y.toLocaleString()})`;
|
||||
}
|
||||
};
|
||||
point.toString() // => "(1000, 2000)"
|
||||
point.toLocaleString() // => "(1,000, 2,000)": note thousands separators
|
||||
```
|
||||
|
||||
### 6.9.3 The valueOf() Method
|
||||
|
||||
`valueOf()`:
|
||||
* is called when JS needs to convert an obj to some non-string primitive type (e.g. number)
|
||||
* Many built-in class has its own `valueOf()`
|
||||
* Date class define its `valueOf()` to convert dates to number, so can perform comparison
|
||||
|
||||
### 6.9.4 The toJSON() Method
|
||||
|
||||
`toJSON()` method:
|
||||
* didn't get defined in `Object.prototype`;
|
||||
* `JSON.stringify()` looks for & invoke it on any object that will be serialized
|
||||
|
||||
```js
|
||||
let point = {
|
||||
x: 1,
|
||||
y: 2,
|
||||
toString: function() { return `(${this.x}, ${this.y})`; },
|
||||
toJSON: function() { return this.toString(); }
|
||||
};
|
||||
JSON.stringify([point]) // => '["(1, 2)"]'
|
||||
```
|
||||
|
||||
## 6.10 Extended Object Literal Syntax
|
||||
|
||||
### 6.10.1 Shorthand Properties
|
||||
|
|
Loading…
Reference in New Issue