코딩 공부/React

[React] ES6 객체와 배열 객체 리터럴 개선 - 가온 코딩

Cosmic-dust 2022. 7. 23. 09:00
728x90
반응형

1. 객체 리터럴 개선

객체 리터럴 개선(object literal enhancement)은 구조 분해의 반대이다.

구조를 다시 만들어내는 과정 또는 내용을 한데 묶는 과정이다.이를 사용하면 현재 영역에 있는 변수를 객체의 필드로 묶을 수 있다.

// Literal Enhancements

var name = "Tallac"
var elevation = 9738

var funHike = {name,elevation}

console.log(funHike)

한글예시

const name = "탈락";    // 캘리포니아에 있는 산
const elevation = 9738; // 고도(단위: 피트)

const funHike = {name, elevation};

console.log(funHike); // {name: "탈락", elevation: 9738}

 

2. 개선된 객체 리터럴로 객체에 메서드 포함시키기

 

이제 funHike 객체에는 name과 elevation이라는 필드가 들어가 있다.

객체 리터럴 개선 또는 객체 재구축을 통해 객체 메서드를 만드는 것도 가능하다.

*아래에서 객체의 키에 접근하기 위해 this를 사용했다는 사실에 유의*

// Literal Enhancements with functions

var name = "Tallac"
var elevation = 9738
var print = function() {
  console.log(`Mt. ${this.name} is ${this.elevation} feet tall`)
}

var funHike = {name,elevation,print}

funHike.print()

한글예시

const name = "탈락";    // 캘리포니아에 있는 산
const elevation = 9738; // 고도(단위: 피트)
const print = function() {
    console.log(`${this.name} 산의 높이는 ${this.elevation} 피트입니다.`)
};

const funHike = {name, elevation,print};

funHike.print(); // 탈락 산의 높이는 9738 피트입니다.

 

 

 

 

객체 메서드를 정의할 때는 더 이상 function 키워드를 사용하지 않아도 된다.

 

객체 리터럴 개선을 통해 현재 영역에서 볼 수 있는 변수들을 객체의 필드에 대입할 수 있으며, function 키워드를 입력하지 않아도 되기 때문에 타이핑해야 할 양이 줄어든다.

 

3-1. 예전 방식의 객체 선언 문법

// Object literals... the old way

var name = "Léo Taillefer"
var sound = "Kahh"

var skier = {
  name: name,
  sound: sound,
  powderYell: function() {
    var yell = this.sound.toUpperCase()
    console.log(`${yell} ${yell} ${yell}!!!`)
  },
  speed: function(mph) {
    this.speed = mph
    console.log('speed:', mph)
  }
}

skier.powderYell()
skier.speed("hair on fire")
console.log(JSON.stringify(skier))

 

 

 

3-2. 새로운 방식의 객체 선언 문법

 

// Object literal enhancements

var name = "Julia Mancuso"
var sound = "go fast"

const skier = {
  name,
  sound,
  powderYell() {
    let yell = this.sound.toUpperCase()
    console.log(`${yell} ${yell} ${yell}!!!`)
  },
  speed(mph) {
    this.speed = mph
    console.log('speed:', mph)
  }
}

skier.powderYell()
skier.speed(350)
console.log(JSON.stringify(skier))

한글예시


var name = "가온"
var sound = "빨리가자"

// 옛날 방식
var skier = {
    name: name,
    sound: sound,
    powderYell: function() {
        var yell = this.sound.toUpperCase();
        console.log(`${yell} ${yell} ${yell}!!!`);
    },
    speed: function(mph) {
        this.speed = mph;
        console.log('속력(mph):', mph);
    }
}

skier.powderYell()
skier.speed("완전 빠름")
console.log(JSON.stringify(skier))
//빨리가자 빨리가자 빨리가자!!!
// 속력(mph): 완전 빠름
// {"name":"가온","sound":"빨리가자","speed":"완전 빠름"}


// 새로운 방식


const skier = {
    name,
    sound,
    powderYell() {
        let yell = this.sound.toUpperCase();
        console.log(`${yell} ${yell} ${yell}!!!`)
    },
    speed(mph) {
        this.speed = mph;
        console.log('속력(mph):', mph);
    }
}

skier.powderYell()
skier.speed(350)
console.log(JSON.stringify(skier))  
// 빨리가자 빨리가자 빨리가자!!!
//속력(mph): 350
//{"name":"가온","sound":"빨리가자","speed":350}

참고자료

러닝 리액트(Learning React), 알렉스 뱅크스, 한빛미디어 (2021)

 

 

728x90
반응형