---
# System prepended metadata

title: '[JS]物件實字的擴展(Object Literal Extensions)'
tags: [' Javascript', ES6]

---

---
tags: ES6, Javascript
disqus: hackmd
---

# [JS]物件實字的擴展(Object Literal Extensions)

[对象的扩展](https://es6.ruanyifeng.com/#docs/object)

[JavaScript ES6 Object Literal Extensions 物件實字的擴展](https://www.fooish.com/javascript/ES6/object-literal-extensions.html)

[[筆記] JavaScript ES6 中的物件的擴展（object literal extension）](https://pjchender.blogspot.com/2017/01/es6-object-literal-extension.html)

---

物件屬性的簡寫：當屬性名稱和變數名稱一樣
```javascript=
const foo = 'bar';

//baz1 等同於 baz2
const baz1 = {foo};
const baz2 = {foo: foo};
```

物件裡的方法也可以簡寫
```javascript=
const a = {
    method: function() {
        return console.log('Hello1');
    }
}

等同於

const a = {
    method() {
        return console.log('Hello2');
    }
}
```

### 定義object屬性

如果忘記表達式可以來這看[javascript的 陳述式、表達式和IIFE](https://hackmd.io/ZPsFqlk5S-aLfQBiBWyZwA?view)
```javascript=
var test = {};

test.foo = true;
test['a' + 'bc'] = 123; //表達式

console.log(test); //{foo: true, abc: 123}
```

如果使用大括號來定義object，在ES5中只有一種方法
```javascript=
var test = {
  foo: true,
  abc: 123
};
```

在ES6使用大括號來定義object，允許大括號裡的屬性名稱使用表達式
```javascript=
let propKey = 'foo';

let test = {
  [propKey]: true,
  ['a' + 'bc']: 123,
  ['h'+'ello']() {
      console.log('hi there!');
  }
};

test //{foo: true, abc: 123, hello: ƒ}
```
