對象的改變分爲對象的擴展和對象的新增方法。this
對象的擴展和新增的方法都有哪些?code
//在ES6中的寫法: const week = 'week'; const year = { week, hello() { console.log('個人名字是', this.name); } }; year; /* { week: "week", hello: ƒ } */ //正常寫法: const week = 'week'; const year = { week, hello:function() { console.log('個人名字是', this.name); } };
const obj = {}; objp['a' + 'bc'] = 123; obj; /*{ abc : 123 }*/
const person = { speakName(){ console.log('hello'); }, }; person.speakName.name; /* "speakName" */
在咱們其餘的一些須要獲取對象枚舉屬性的時候,也就是獲取對象的key,對象的方法時,若是有了這個enumerale可枚舉性,那麼咱們才能獲取獲得;反之,沒有的話就獲取不到。常見的有四個:對象
let obj = { week: 123 }; Object.getOwnPropertyDescriptor(obj, 'week'); /* { value: 123, writable: true, enumerable: true, configurable: true } */
for ( s in { [Symbol()]:0, b:0, 10:0, 2:0, a:0 }) { console.log(s) } /* 2 10 b a */
Object.keys({ [Symbol()] : 0, b:0, 10:0, a:0 }) /* ['2', '10', 'b', 'a'] */
for in 和 object.keys都是同樣的,先返回數字的枚舉而後再返回字母枚舉,最後若是有Symbol就返回固然了object.keys是不支持Symbol的。繼承
Object.getOwnProertySymbol({ [Symbol()] : 0, b:0, 10:0, a:0 }) /* [Symbol()] */
Object.getOwnPropertyNames({ [Symbol()]:0, b:0, 10:0, 2:0, a:0 }) /* ["2", "10", "b", "a"] */
Reflect.ownKeys({ [Symbol()]:0, b:0, 10:0, 2:0, a:0 }) /* ['2', '10', 'b', 'a', Symbol()] */
順序——數字——字符——Symbolip
在ES6中,super是指向當前對象的原型對象(只能用在對象的方法之中)element
const proto = { week: 'hello' }; const obj = { week: 'world', find() { return super.week; } }; obj.__proto__ = proto; // Object.setPrototypeOf(obj, proto); obj.find(); /* "hello" */ const obj = { week: super.week } /* SyntaxError: 'super' keyword unexpected here */ const obj = { week: () => super.week } /* SyntaxError: 'super' keyword unexpected here */ const obj = { week: function () { return super.week } } /* SyntaxError: 'super' keyword unexpected here */
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; x; /* 1 */ y; /* 2 */ z; /* { a: 3, b: 4 } */ let { ...z } = null; /* TypeError: Cannot destructure 'undefined' or 'null'. */ let { ...z } = undefined; /* TypeError: Cannot destructure 'undefined' or 'null'. */ let { ...x, y, z } = { x: 1, y: 2, a: 3, b: 4 }; /* Uncaught SyntaxError: Rest element must be last element */
let z = { a: 3, b: 4 }; let n = { ...z }; n; /* { a: 3, b: 4 } */ let week = { ...['a', 'b', 'c'] }; week /* { 0: "a", 1: "b", 2: "c" } */ {...'hello'} /* { 0: "h", 1: "e", 2: "l", 3: "l", 4: "o" } */ let ab = { ...a, ...b }; let ab = Object.assign({}, a, b); let aWithXGetter = { ...a, get x() { throw new Error('not throw yet'); } }; /* */