ES6中對象新增了哪些擴(kuò)展?

1、屬性的簡寫
ES6中,當(dāng)對象鍵名與對應(yīng)值名相等的時候,可以進(jìn)行簡寫。
const o = {method() {return "Hello!";}};// 等同于const o = {method: function() {return "Hello!";}}
在函數(shù)內(nèi)作為返回值,也會變得方便很多。
const obj = {f() {this.foo = 'bar';}};new obj.f() // 報(bào)錯
2、屬性名表達(dá)式
ES6 允許字面量定義對象時,將表達(dá)式放在括號內(nèi)。
let obj = {['h' + 'ello']() {return 'hi';}};obj.hello() // hi
注意,屬性名表達(dá)式與簡潔表示法,不能同時使用,會報(bào)錯。
const keyA = {a: 1};const keyB = {b: 2};const myObject = {[keyA]: 'valueA',[keyB]: 'valueB'};myObject // Object {[object Object]: "valueB"}
3、super關(guān)鍵字
this 關(guān)鍵字總是指向函數(shù)所在的當(dāng)前對象,ES6 又新增了另一個類似的關(guān)鍵字 super ,指向當(dāng)前對象的原型對象。
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };x // 1y // 2z // { a: 3, b: 4 }
注意:解構(gòu)賦值必須是最后一個參數(shù),否則會報(bào)錯
解構(gòu)賦值是淺拷貝。
Reflect.ownKeys({ [Symbol()]:0, b:0, 10:0, 2:0, a:0 })// ['2', '10', 'b', 'a', Symbol()]
4、對象新增的方法
關(guān)于對象新增的方法,分別有以下:
Object.is()
Object.assign()
Object.getOwnPropertyDescriptors()
Object.setPrototypeOf(),Object.getPrototypeOf()
Object.keys(),Object.values(),Object.entries()
Object.fromEntries()
1)、Object.is()
嚴(yán)格判斷兩個值是否相等,與嚴(yán)格比較運(yùn)算符(===)的行為基本一致,不同之處只有兩個:一是 +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() 方法是淺拷貝,遇到同名屬性會進(jìn)行替換。
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)屬性的鍵對應(yīng)值的數(shù)組。
const obj = { foo: 'bar', baz: 42 };Object.entries(obj)// [ ["foo", "bar"], ["baz", 42] ]
5)、Object.fromEntries()
用于將一個鍵值對數(shù)組轉(zhuǎn)為對象。
<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 }
參考文獻(xiàn):https://es6.ruanyifeng.com/#docs/object
學(xué)習(xí)更多技能
請點(diǎn)擊下方公眾號
![]()

評論
圖片
表情
