Skip to content

Latest commit

 

History

History
executable file
·
293 lines (232 loc) · 6.26 KB

7. enhanced object functionalities.md

File metadata and controls

executable file
·
293 lines (232 loc) · 6.26 KB

7. enhanced object functionalities (객체의 향상된 기능들)

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
}

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] && fullFileNameArr[1] === 'png' ? 'jpg' : 'gif'
  return {
    filename,
    ext
  }
}
convertExtension('abc.png')

2) destructuring assignment

const {
  name,
  age
} = {
  name: '재남',
  age: 30
}
console.log(name, age)

7-2. concise methods (간결한 메소드)

7-2-1. 소개

var obj = {
  name: 'foo',
  getName: function () { return this.name } // prototype 프로퍼티가 있음
}
const obj = {
  name: 'foo',
  getName () { return this.name } // prototype 프로퍼티가 없음 - 생성자로 사용되는 것 제한
}

7-2-2. 상세

1) :function 키워드 제거

2) super 명렁어로 상위 클래스에 접근 가능

  • this__proto__. = super
const Person = {
  greeting: function () { return 'hello' }
}
const friend = {
  greeting: function () {
    return 'hi, ' + super.greeting()
  }
}
Object.setPrototypeOf(friend, Person) // friend 의 프로토타입을 Person으로 지정하라 

// 위 함수는 실제로 다음과 같다.
const Person2 = function (){}
Person2.prototype.greeting = function () {return 'hello'}

const frined = new Person2();
friend.greeting = function (){
  return 'hi, ' + this.__proto__.greeting();
}


friend.greeting()
const Person = {
  greeting () { return 'hello' }
}
const friend = {
  greeting () {
    return 'hi, ' + super.greeting()
  }
}
Object.setPrototypeOf(friend, Person)
friend.greeting()

3) prototype 프로퍼티가 없음 -> 생성자함수로?

  • 함수의 생성자로서의 기능 제한
  • 함수가 가벼워짐(객체(프로토타입)를 담고 있는 프로퍼티가 하나 없어졌으니까)
const Person = {
  greeting () { return 'hello' }
}
const p = new Person.greeting() //Uncaught TypeError: Person.greeting is not a constructor

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 property name (계산된 프로퍼티명)

7-3-1. 소개

var className = ' Class'
var obj = {}

// 오류
obj.'ab cd' = 'AB CD' // Unexpected string

// 됨
obj = {
  'ab cd': 'AB CD'
}

// 됨
obj['ab cd'] = 'AB CD'

// 오류 (근데 이거는 되야할거 같은데)
var obj = {
  'A' + className: 'A급'
}

//됨 (이게 되면 위에도 되야하지않을까?)
obj['A' + className] = 'A급'

// 되게 만들어보자 (대괄호 표기법을 객체 내부에서도 사용가능하도록 허용)
const obj2 = {
  ['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 (고정된 프로퍼티 열거 순서)

// 1)
const obj1 = {
  c: 1,
  2: 2,
  a: 3,
  0: 4,
  b: 5,
  1: 6
}
const keys1 = []
for (const key in obj1) {
  keys1.push(key)
}
console.log(keys1) // ["0", "1", "2", "c", "a", "b"]
console.log(Object.keys(obj1)) // ["0", "1", "2", "c", "a", "b"]
console.log(Object.getOwnPropertyNames(obj1)) // ["0", "1", "2", "c", "a", "b"]

// 2)
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) // ["2", "10", "02", "01"]
console.log(Object.keys(obj2)) // ["2", "10", "02", "01"]
console.log(Object.getOwnPropertyNames(obj2)) // ["2", "10", "02", "01"]
console.log(Reflect.ownKeys(obj2)) // ["2", "10", "02", "01", Symbol(2), Symbol(1)]

const obj3 = Object.assign({}, obj1, obj2)
const keys3= []
for(const key in obj3) {
  keys3.push(key)
}
console.log(keys3) 
// ["0", "1", "2", "10", "c", "a", "b", "02", "01"]
console.log(Object.keys(obj3)) 
// ["0", "1", "2", "10", "c", "a", "b", "02", "01"]
console.log(Object.getOwnPropertyNames(obj3)) 
// ["0", "1", "2", "10", "c", "a", "b", "02", "01"]
console.log(Reflect.ownKeys(obj3)) 
// ["0", "1", "2", "10", "c", "a", "b", "02", "01", Symbol(2), Symbol(1)]

1) 열거순서는 다음 규칙을 따른다.

  • number &rarr string &rarr symbol 의 순서로 정렬된다.
  • number key는 프로퍼티들 중 가장 앞에 위치하며, 오름차순이다.
  • string key는 객체에 추가된 당시의 순서를 유지하면서 숫자 뒤에 위치한다.
  • Symbol key는 객체에 추가된 당시의 순서를 유지하면서 제일 마지막에 위치한다.

2) number(index)로 인식하는 key는 다음과 같다.

  • 객체 프로퍼티의 key는 원래 문자열

  • 0 이상의, 첫째자리가 0이 아닌 수는, 문자열로 입력해도 똑같이 숫자로 인식한다.

  • 첫째자리가 0인 두자리 이상의 숫자는 문자열로 입력해야 하고, 문자열로 인식한다.

  • 음수는 문자열로 입력해야 하고, 문자열로 인식한다.

∴ 'index'로 인식할 수 있는 경우에 한해서만 작은 수부터 나열한다.

3) 열거순서를 엄격히 지키는 경우는 다음과 같다.

  • Object.getOwnPropertyNames()
  • Reflect.ownKeys()
  • Object.assign()

4) ES5 하위문법인 다음의 경우에는 정합성을 보장하지 않는다.(순서를 보장하지 않음)

  • for in
  • Object.keys()
  • JSON.stringify()