1. 属性的简洁表示方法 允许在对象之中,直接写变量,这时,属性名为变量名,属性值为变量的值。 function f(x, y) { return {x, y}; } //等同于 function f1(x, y) { return {x : x, y: y}; } console.log(f(1, 2));
2. 除了属性方法也可以简写 const o = { method(){ return "hello!"; } }; //等同于 const o = { method : function () { return "hello!" } }; CommonJs 输出变量适合使用简洁写法 module.exports = {getItem, setItem, clear}; //等同于 module.exports = { getItem : getItem, setItem : setItem, clear : clear };
属性的赋值器setter 和取值器(getter) ,的简写方式 const cart = { _wheels : 4, get wheels (){ return this._wheels; }, set wheels(value){ if(value < this._wheels){ throw new Error('数值太小了!'); } this._wheels = value; } }
如果某个方法的值是一个Generator函数,前面需要加上星号 const obj = { * m(){ yield 'hello world'; } }
3. 属性名表达式 //方法一: obj.foo = true; //方法二: obj['a' + 'bc'] = 123; //字面量方式(使用大括号)定义对象,只能如下 var obj = { foo : true, abc : 123 } //ES6 中允许表达式定义属性如: let propKey = 'foo'; let obj = { [propKey] : true, ['a' + 'bc'] : 123 }; //表达式还可以用于定义方法名 let obj = { ['h' + 'ello'](){ return 'hi'; } }; obj.hello(); //h1
//注意属性名不能是对象,虽然不报错。默认情况下会将对象自动转换为[object object] 这点要特别小心。 const keyA = {a: 1}; const keyB = {b : 2}; const myObject = { [keyA] : 'valueA', [keyB] : 'valueB' } console.log(myObject); //{ '[object Object]': 'valueB' }
4. 方法的name 属性 const person = { sayName(){ console.log('hello!'); } }; console.log(person.sayName.name) // sayName //如果对象的方法使用了getter setter const obj ={ get foo(){}, set foo(x){} }; //obj.foo.name; //这样不行的,报错 const descriptor = Object.getOwnPropertyDescriptor(obj, 'foo'); console.log(descriptor); descriptor.get.name; console.log(descriptor.set.name); // set foo //bind Function创建的 (new Function()).name // "anonymous" var doSomething = function() { // ... }; doSomething.bind().name // "bound doSomething"
5. 如果对象的方法是一个Symbol值,那么name属性返回的是这个Symbol值的描述。 const key1 = Symbol('description'); const key2 = Symbol(); let obj = { [key1](){}, [key2](){} } console.log(obj[key1].name); // [description] console.log(obj[key2].name); // //空
参考: http://es6.ruanyifeng.com/#docs/object (写的很好!?)