Finished Chapter 6.5: Testing Properties
parent
0ab5798d1b
commit
35212b2b19
|
@ -288,6 +288,60 @@ delete globalThis.x; // This works
|
|||
|
||||
## 6.5 Testing Properties
|
||||
|
||||
JS obj = sets of properties. We want to test membership in the set using:
|
||||
* `in` operator
|
||||
* `hasOwnProperty()` method
|
||||
* `propertyIsEnumerable()` method
|
||||
* querying property
|
||||
|
||||
`in` operator return true if object has an own property or an inherited property **by that name**:
|
||||
```js
|
||||
let o = { x: 1 };
|
||||
"x" in o // => true: o has an own property "x"
|
||||
"y" in o // => false: o doesn't have a property "y"
|
||||
"toString" in o // => true: o inherits a toString property
|
||||
```
|
||||
|
||||
`hasOwnProperty()` method of an obj return:
|
||||
* `true` if obj has an own property with the given name
|
||||
* `false` for inherited properties
|
||||
```js
|
||||
let o = { x: 1 };
|
||||
o.hasOwnProperty("x") // => true: o has an own property x
|
||||
o.hasOwnProperty("y") // => false: o doesn't have a property y
|
||||
o.hasOwnProperty("toString") // => false: toString is an inherited property
|
||||
```
|
||||
|
||||
`propertyIsEnumerable()` refines `hasOwnProperty()`. It returns:
|
||||
* `true` if named property is not inherited and its *enumerable* attribute is `true`
|
||||
* Properties created by normal JS code are enumerable unless specified
|
||||
```js
|
||||
let o = { x: 1 };
|
||||
o.propertyIsEnumerable("x") // => true: o has an own enumerable property x
|
||||
o.propertyIsEnumerable("toString") // => false: not an own property
|
||||
Object.prototype.propertyIsEnumerable("toString") // => false: not enumerable
|
||||
```
|
||||
|
||||
Qeurying method is simple by using `!=` to make sure whether property is undefined
|
||||
```js
|
||||
let o = { x: 1 };
|
||||
o.x !== undefined // => true: o has a property x
|
||||
o.y !== undefined // => false: o doesn't have a property y
|
||||
o.toString !== undefined // => true: o inherits a toString property
|
||||
```
|
||||
|
||||
Simple querying method vs. `in` operator:
|
||||
* `in` operator can tell whether a property does not exit (`null`) or exit but not defined (`undefined`)
|
||||
```js
|
||||
let o = { x: undefined }; // Property is explicitly set to undefined
|
||||
o.x !== undefined // => false: property exists but is undefined
|
||||
o.y !== undefined // => false: property doesn't even exist
|
||||
"x" in o // => true: the property exists
|
||||
"y" in o // => false: the property doesn't exist
|
||||
delete o.x; // Delete the property x
|
||||
"x" in o // => false: it doesn't exist anymore
|
||||
```
|
||||
|
||||
## 6.6 Enumerating Properties
|
||||
|
||||
### 6.6.1 Property Enumeration Order
|
||||
|
|
Loading…
Reference in New Issue