ES6中对象新增了哪些扩展?

1、属性的简写
ES6中,当对象键名与对应值名相等的时候,可以进行简写。
const o = {method() {return "Hello!";}};// 等同于const o = {method: function() {return "Hello!";}}
在函数内作为返回值,也会变得方便很多。
const obj = {f() {this.foo = 'bar';}};new obj.f() // 报错
2、属性名表达式
ES6 允许字面量定义对象时,将表达式放在括号内。
let obj = {['h' + 'ello']() {return 'hi';}};obj.hello() // hi
注意,属性名表达式与简洁表示法,不能同时使用,会报错。
const keyA = {a: 1};const keyB = {b: 2};const myObject = {[keyA]: 'valueA',[keyB]: 'valueB'};myObject // Object {[object Object]: "valueB"}
3、super关键字
this 关键字总是指向函数所在的当前对象,ES6 又新增了另一个类似的关键字 super ,指向当前对象的原型对象。
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };x // 1y // 2z // { a: 3, b: 4 }
注意:解构赋值必须是最后一个参数,否则会报错
解构赋值是浅拷贝。
Reflect.ownKeys({ [Symbol()]:0, b:0, 10:0, 2:0, a:0 })// ['2', '10', 'b', 'a', Symbol()]
4、对象新增的方法
关于对象新增的方法,分别有以下:
Object.is()
Object.assign()
Object.getOwnPropertyDescriptors()
Object.setPrototypeOf(),Object.getPrototypeOf()
Object.keys(),Object.values(),Object.entries()
Object.fromEntries()
1)、Object.is()
严格判断两个值是否相等,与严格比较运算符(===)的行为基本一致,不同之处只有两个:一是 +0 不等于 -0 ,二是 NaN 等于自身。
const target = { a: 1, b: 1 };const source1 = { b: 2, c: 2 };const source2 = { c: 3 };Object.assign(target, source1, source2);target // {a:1, b:2, c:3}
注意:Object.assign() 方法是浅拷贝,遇到同名属性会进行替换。
2)、Object.getOwnPropertyDescriptors()
返回指定对象所有自身属性(非继承属性)的描述对象。
Object.setPrototypeOf(object, prototype)// 用法const o = Object.setPrototypeOf({}, null);
3)、Object.getPrototypeOf()
用于读取一个对象的原型对象。
var obj = { foo: 'bar', baz: 42 };Object.keys(obj)// ["foo", "baz"]
4)、Object.values()
返回自身的(不含继承的)所有可遍历(enumerable)属性的键对应值的数组。
const obj = { foo: 'bar', baz: 42 };Object.entries(obj)// [ ["foo", "bar"], ["baz", 42] ]
5)、Object.fromEntries()
用于将一个键值对数组转为对象。
<span https:="" mmbiz.qpic.cn="" mmbiz_png="" gh31uf9viibsicupllhibkmhwgisayicslpfw98bn0wtoribadfzphyw02ohvdc5g0ocdbshb7iixuxpkpnyvletfq="" 640?wx_fmt="png")" 10px="" 40px="" no-repeat="" rgb(30,="" 30,="" 30);height:="" 30px;width:="" 100%;margin-bottom:="" -7px;border-radius:="" 5px;"="">Object.fromEntries([['foo', 'bar'],['baz', 42]])// { foo: "bar", baz: 42 }
参考文献:https://es6.ruanyifeng.com/#docs/object
学习更多技能
请点击下方公众号
![]()

评论
