7-1. shorthand properties (프로퍼티 축약)
7-1-1. 소개
var x = 10
var y = 20
var obj = {
x: x,
y: y
}
const x = 10
const y = 20
const obj = {
x,
y
}
shorthand properties는 한번씩만 쓰면 그것이 key이자 value가 된다.
7-1-2. 상세
프로퍼티의 key와 value에 할당할 변수명이 동일한 경우 value 생략 가능.
7-1-3. 활용
1)함수에서 객체를 리턴할 때
const convertExtension = function (fullFileName) {
const fullFileNameArr = fullFileName.split('.')
const filename = fullFileNameArr[0]
const ext = fullFileNameArr[1] === 'png' ? 'jpg' : 'gif'
return {
filename,
ext
}
}
convertExtension('abc.png')
2) destructuring assignment
const {
name,
age
} = {
name: '재남',
age: 30
}
console.log(name, age)
객체를 매칭하여서 name이라는 변수에 재남,
age라는 변수에 concise methods (간결한 메소드)을 넣겠다 라는 것이다.
변수선언을 두개를 한꺼번에 한 것이다.
7-2. concise methods (간결한 메소드)
7-2-1. 소개
var obj = {
name: 'foo',
getName () { return this.name }
getName2: function (){ return this.name }
}
getName은 function 을 쓰지 않고 축약형으로 나타내었고
getName2는 function을 명시한 것이다. 이 둘을 console.dir로 보자.
1. 메소드축약형을 열어보면 arguments,caller에 invoke를 해야지만 알 수 있다.
실행환경 당시에서 값을 접근하는 것이 아니라 외부 스코프에서 이미 함수가 종료된 이후에 접근을 하려니까 error를 띄어준다.
반면 축약형을 사용 하지 않은 getName2는 종료된 이후에 접근을 하려해도 접근이 된다. 다만 값이 null일 뿐이다.
2. 메소드축약형에는 prototype이 없다. 이것이 의미하는 바는
const a = new obj.getName(); 이 불가능하다. 생성자 함수로서는 동작이 불가능하다. 오로지 함수 본연의 기능만을 가지고 있다.
그렇다면 단점만 있을 까? 그런 것은 아니다. 축약형은 그 대신에 함수가 가벼워졌다. prototype property라는 하나의 객체가 없어졌다. 성능은 올라갈 것이다.
7-2-2. 상세
1) `:function` 키워드 제거
2) `super` 명렁어로 상위 클래스에 접근 가능
const Person = {
greeting: function () { return 'hello' }
}
const friend = {
greeting: function () {
return 'hi, ' + super.greeting()
}
}
Object.setPrototypeOf(friend, Person)
friend.greeting()
Object.setPrototypeof는 friend의 prototype을 Person으로 해라라는 것을 의미한다.
즉 instance는 friend로 Person을 생성자 함수로 하라는 것을 의미한다.
super라는 접근자에 의해서 자신의 protoype의 상위의 메소드를 바로 호출 할 수 있게 된다.
Object.setPrototypeOf(friend, Person)
이 명령에 의해서
friend.__proto__ = { greeting : funciton(){} } 가 들어가게 된다.
-----------------------
const Person2 = function (){}
Person2.prototype.greeting = function () {return 'hello'}
const friend = new Person2();
friend.greeting = function (){}
return 'hi, ' +this.__proto__.greeting();
3) `prototype` 프로퍼티가 없음 -> 생성자함수로?
const Person = {
greeting () { return 'hello' }
}
const p = new Person.greeting()
4) 그밖에는 모두 기존 함수/메소드와 동일
const obj = {
a () { console.log('obj log') },
log () { console.log(this) }
}
console.log(obj.a.name)
setTimeout(obj.a, 1000)
obj.log()
obj.log.call([])
setTimeout(obj.log.bind('haha'), 2000)
7-3. computed propertycomputed property name (계산된 프로퍼티명)
7-3-1. 소개
var className = ' Class'
var obj = {}
obj.'ab cd' = 'AB CD'
//error 발생 .을 찍고 뒤에 문자열 불가
obj = {
'ab cd': 'AB CD'
}
//객체안에 가능
obj['ab cd'] = 'AB CD'
//대괄호 안에 '' 가능
var obj = {
'A' + className: 'A급'
}
// 불가능
obj['A' + className] = 'A급'
//가능
const obj2 = {
'ab cd':
['A' + className]: 'A급'
}
//대괄호 표기법을 객체 안에서 사용하면 가능
let suffix = ' name'
let iu = {
['last' + suffix]: '이',
['first' + suffix]: '지은'
}
console.log(iu)
const count = (function (c) {
return function () {
return c++
}
})(0)
var obj = {
[`a_${count()}`]: count(),
[`a_${count()}`]: count(),
[`a_${count()}`]: count()
}
console.log(obj)
7-3-2. 상세
1) 객체 리터럴 선언시 프로퍼티 키값에 대괄호 표기로 접근 가능
2) 대괄호 내에는 값 또는 식을 넣어 조합할 수 있음
7-4. own property enumeration order (고정된 프로퍼티 열거 순서)
const obj2 = {
[Symbol('2')]: true,
'02': true,
'10': true,
'01': true,
'2': true,
[Symbol('1')]: true
}
const keys2= []
for(const key in obj2) {
keys2.push(key)
}
console.log(keys2)
//숫자가 먼저 오고, 작은수에서 큰수의 순서로, 문자열은 입렫된 순서 그대로
//숫자인데 첫글자가 0이 아닌 경우 -> 숫자로 인식
console.log(Object.keys(obj2))
console.log(Object.getOwnPropertyNames(obj2))
console.log(Reflect.ownKeys(obj2))
//symbole은 열거대상에서 제외되는데 Reflect.ownKeys(obj2) 를 통해서 symbol까지 출력가능
#### 1) 열거순서는 다음 규칙을 따른다.
- **number &rarr string &rarr symbol** 의 순서로 정렬된다.
- `number` key는 프로퍼티들 중 가장 앞에 위치하며, 오름차순이다.
- `string` key는 객체에 추가된 당시의 순서를 유지하면서 숫자 뒤에 위치한다.
- `Symbol` key는 객체에 추가된 당시의 순서를 유지하면서 제일 마지막에 위치한다.
#### 2) number(index)로 인식하는 key는 다음과 같다.
- 0 이상의, 첫째자리가 0이 아닌 수는, 문자열로 입력해도 똑같이 숫자로 인식한다.
- 첫째자리가 0인 두자리 이상의 숫자는 문자열로 입력해야 하고, 문자열로 인식한다.
- 음수는 문자열로 입력해야 하고, 문자열로 인식한다.
**∴ 'index'로 인식할 수 있는 경우에 한해서만 작은 수부터 나열한다.**
#### 3) 열거순서를 엄격히 지키는 경우는 다음과 같다.
Object.getOwnPropertyNames()
Reflect.ownKeys()
Object.assign()
#### 4) ES5 하위문법인 다음의 경우에는 정합성을 보장하지 않는다.
for in
Object.keys()
JSON.stringify()