mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2024-04-21 12:32:22 +00:00
docs: update ES2022
This commit is contained in:
@@ -833,3 +833,31 @@ Object.fromEntries(map)
|
||||
Object.fromEntries(new URLSearchParams('foo=bar&baz=qux'))
|
||||
// { foo: "bar", baz: "qux" }
|
||||
```
|
||||
|
||||
## Object.hasOwn()
|
||||
|
||||
JavaScript 对象的属性分成两种:自身的属性和继承的属性。对象实例有一个`hasOwnProperty()`方法,可以判断某个属性是否为原生属性。ES2022 在`Object`对象上面新增了一个静态方法[`Object.hasOwn()`](https://github.com/tc39/proposal-accessible-object-hasownproperty),也可以判断是否为自身的属性。
|
||||
|
||||
`Object.hasOwn()`可以接受两个参数,第一个是所要判断的对象,第二个是属性名。
|
||||
|
||||
```javascript
|
||||
const foo = Object.create({ a: 123 });
|
||||
foo.b = 456;
|
||||
|
||||
Object.hasOwn(foo, 'a') // false
|
||||
Object.hasOwn(foo, 'b') // true
|
||||
```
|
||||
|
||||
上面示例中,对象`foo`的属性`a`是继承属性,属性`b`是原生属性。`Object.hasOwn()`对属性`a`返回`false`,对属性`b`返回`true`。
|
||||
|
||||
`Object.hasOwn()`的一个好处是,对于不继承`Object.prototype`的对象不会报错,而`hasOwnProperty()`是会报错的。
|
||||
|
||||
```javascript
|
||||
const obj = Object.create(null);
|
||||
|
||||
obj.hasOwnProperty('foo') // 报错
|
||||
Object.hasOwn(obj, 'foo') // false
|
||||
```
|
||||
|
||||
上面示例中,`Object.create(null)`返回的对象`obj`是没有原型的,不继承任何属性,这导致调用`obj.hasOwnProperty()`会报错,但是`Object.hasOwn()`就能正确处理这种情况。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user