객체 만들기 (key)


//옛날 문법
let name = "hwonda";
let age = 29;
let person ={name:name, age:age}
//ES6 문법
let name = "hwonda";
let age = 29;
let person ={name, age}

: 자동으로 변수 이름 = key 값으로 변경해줍니다.

 

객체 분해하기


//옛날 문법
let person = {
    name : "hwonda",
    age : 29
    }
let name = person.name;
let age = person.age;
//ES6 문법
let person = {
    name : "hwonda",
    age : 29
}
let {name, age} = person;

: 객체 만들기와 동일하게 변수값 = key값 일때만 가능합니다.

 

${...}


//옛날 문법
let name = "hwonda";
let age = 29;
console.log("이름은"+name+"입니다. 나이는"+age"입니다");
//ES6 문법
let name = "hwonda";
let age = 29;
console.log(`이름은 ${name}입니다. 나이는 ${age}입니다`);

: ${} 을 사용할때는 작은 따옴표(')가 아닌, 백틱(`)을 사용합니다.

 

배열


//옛날 문법
let array = [1, 2, 3];
let a = array[0];
let b = array[1];
let c = array[2];
console.log(a,b,c);

// 결과 
// 1 2 3
//ES6 문법
let array = [1, 2, 3];
let [a, b, c] = array
let [first,...rest] = array

console.log(a, b, c)
console.log(first)
console.log(rest)

// 결과
// 1 2 3
// 1
// [2, 3]

: rest가 아니더라도 주고싶은 변수 이름은 쓰면 됩니다. (others, userInfo 등등..)

 

...의 추가 기능


let person = {
    name : "hwonda",
    age : 29,
    sex : male
}

let {name,...userInfo} = person
console.log(name, userInfo)

// 결과
// hwonda { age : 29, sex : male}
// 객체 분해 및 생성 가능

 

...의 추가 기능 2

// 옛날 문법
let a = [1,2];
let b = [3,4];
let c = [5,6];

let result = a.concat(b,c)
console.log(result)

// 결과
// [1, 2, 3, 4, 5, 6]
// ES6 문법
let a = [1,2];
let b = [3,4];
let c = [5,6];

let result = [...a,...b,...c]
console.log(result)

// 결과
// [1, 2, 3, 4, 5, 6]

 

함수


// 옛날 문법
function boo(){
    console.log("hello")
}
// ES6 문법
let boo = ()=>{
    console.log("hello")
}

: 함수 선언 방식을 바꿔버렸습니다. 왜 굳이 만들었을까요?

function boo(){
    return "haha"
}

이 함수는 아래와 같이 편하게 쓸 수 있습니다. (return 생략 가능, 문장 1개의 함수를 1줄로 표현 가능)

let boo = ()=>"haha"

그러나 화살표 함수(=>)는 100% 옛날 문법을 대체할 순 없습니다. (this)

 

this 란?


let age = 19
let person = {
    name : "hwonda",
    age : 29
    getInfo:function(){
        console.log(age)
    }
}

person.getInfo()

// 결과
// 19

: 분명 getInfo의 함수를 호출했으나, 결과는 놀랍게도 전역변수를 가져옵니다.

이 때, console.log(this.age)를 하는 경우, 지역변수 값인 29를 가지고 올 수 있게 됩니다.

this는 곧 나를 불러준 객체라고 볼 수 있습니다.

let age = 19
let person = {
    name : "hwonda",
    age : 29
    getInfo:function(){
        console.log(this.age)
    }
}

person.getInfo()

// 결과
// 29

: 그러나 getInfo()=>{console.log(this.age)}로 함수를 선언할 경우, undefined 오류가 발생한다. (결국 this값을 찾다가찾다가 Window에 있는 person값을 가져와 undefinded 되는 것.)

+ Recent posts