Node.js

구조분해할당

babydeve 2023. 6. 28. 22:18

1. 구조분해할당이란?

: 구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식

- 1:1로 변수에 값을 담음. 

-나머지연산자로 1:다수로 값을 담을 수 있음.

//배열
var a, b, rest;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

//배열, 나머지연산자
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

//객체
({ a, b } = { a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20

//객체, 나머지연산자
({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}

2. 대상에 this를 사용하는 경우 구조분해할당을 하면 문제가 생긴다.

var candyMachine = {
	status: {
    	name: 'node',
        count: 5
    },
    getCandy: function( ){
    	this.status.count--
        return this.status.count
    },
};
var getCandy = candyMachine.getCandy;
var count = candyMachine.status.count
const {getCandy, status: {count}} = candyMachine  //this가 있으면 구조분해할당을 할 수 없음.
728x90