[웹] ES2015+ 문법

1. const 와 let

const, let : 블록스코프

var : 함수스코프

  • 함수스코프
    - function() {}이 스코프의 기준점
    - if나 for, while은 영향을 미치지 못함

  • 블록스코프
    - const와 let은 함수 및 블록({})에도 별도의 스코프를 가진다.

if(true) {
    var x = 3;
    const y = 3;
}

console.log(x);
console.log(y); //ERROR : const키워드는 블록스코프이기때문에 외부에서는 알 수가 없다.

const

  • 상수는 다른 값으로 변경이 불가능하다. (변경하고 싶으면 let으로)
  • 상수는 반드시 선언과 동시에 초기화가 필요하다. (초기화하지 않고 선언하면 에러)
const a = 0;
a = 1; //ERROR : 상수는 값 변경이 안됨.

let a = 0;
a = 1; //가능
console.log(a);

const c; //ERROR : 상수는 반드시 선언과 동시에 초기화해줘야 한다.


2. 백틱기호를 이용하여 문자열 합치기

${변수}

- 문자열을 합칠 때 + 기호때문에 지저분하고 불편하다.
- ES2015부터는 ` (백틱)기호 사용 가능
- 백틱 문자열 안에 ${변수}처럼 사용

//출력결과 : 1 더하기 2는 '3'  1 더하기 2는 '3'

var num1 = 1;
var num2 = 2;
var result = 3;
var str = num1 + ' 더하기 ' + num2 + '는 \'' + result + '\'';
console.log(str);

const str2 = `${num1} 더하기 ${num2}는 '${result}'`;
console.log(str2);


3. 객체 리터럴

  • ES5 시절의 객체 표현 방법
    (객체 리터럴 안에서 선언할 수 없었음)
var sayNode = function() {
    console.log('Node');
};

var es = 'ES';

var oldObject = {
    sayJs: function() {
        console.log('JS')
    },
    sayNode: sayNode
};

oldObject[es + 6] = 'Fantastic'; //기존 : 객체 리터럴 안에서 선언할 수 없었음

oldObject.sayNode(); //Node
oldObject.sayJs(); //JS
console.log(oldObject.ES6); //Fantastic

  • ES6부터는 훨씬 간결한 문법으로 객체 리터럴 표현 가능
    - 객체의 메서드에 : function을 붙이지 않아도 된다.
    - {sayNode: sayNode}와 같은 것을 {sayNode}로 축약 가능
    - [변수+값]등으로 동적 속성명을 객체 속성명으로 사용 가능
//ES2015 최신문법 적용 후
var sayNode = function() {
    console.log('Node');
};

const newObject = {
    sayJS() { //이전: sayJs: function{} 안해도 됨
        console.log('JS');
    },
    sayNode, //이전: sayNode: sayNode
    [es+6]: 'Fantastic' //이전: newObject[es+6] = 'Fantastic'
    //현재: 객체리터럴 안에서 사용 가능

}
newObject.sayNode();
newObject.sayJS();
console.log(newObject['ES6']);

//결과: Node JS Fantastic이 2번 나온다.

4. 화살표 함수

  • {}본문이 한 줄일 경우 {}괄호 생략 가능
function add1(x, y) {
    return x+y;
}

const add2 = (x, y) => {
    return x+y;
}

const add3 = (x, y) => x+y; //{}안의 내용이 한 줄일 경우에만 {}생략가능

console.log(add1(1,3));
console.log(add2(1,3));
console.log(add3(1,3));

//매개변수가 하나면 ()괄호 생략 가능

function not1(x) {
    return !x;
}

const not2 = x => !x; //매개변수가 하나인 경우 괄호 생략 가능

console.log(not1(true));
console.log(not2(true));


4-1. 화살표 함수의 this

- ES2015 이전

var relationship = {
    name: 'zero',
    friends: ['nero', 'hero', 'xero'],
    logFriends: function() {
        console.log("THIS1", this); //this: relationship 객체

        var that = this;
        this.friends.forEach(function(friend) {
            console.log("THIS2", this); //this: 전역객체

            console.log(that.name, friend);
        })
    }
}

relationship.logFriends();



- ES2015 이후

화살표 함수의 this는 상위컨텍스트의 this를 그대로 물려받는다.

const relationship2 = {
    name: 'zero',
    friends: ['nero', 'hero', 'xero'],
    logFriends() {
        console.log("THIS3", this); //this: relationship2 객체

        this.friends.forEach(friend => { //화살표함수에서 this는 상위컨텍스트의 this를 가져옴, 따로 that변수에 this할당할 필요X
            console.log("THIS4", this); //this : relationship2 객체


            console.log(this.name, friend);
        })
    }
}
relationship2.logFriends();


5. 구조분해할당

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

구조분해할당

const { 변수 } = 객체; 로 객체 안의 속성을 변수명으로 사용 가능
-> 외부에서 언제든지 count호출 가능

  • 단, getCandy()를 실행했을 때 결과가 candyMachine.getCandy()와는 달라지므로 주의
  • count처럼 속성 안의 속성도 변수명으로 사용 가능

var candyMachine = {
    status: {
        name: 'node',
        count: 5
    },
    getCandy: function() {
        console.log(`Candy: ${this.status.count}`);
    }
}

//--(1)구조분해할당 이전 : cnadyMachine. 을 꼭 붙여줘야 접근 가능
candyMachine.getCandy(); 
console.log(candyMachine.status.count);

//--(2)개별 변수에 담음
var getCandy = candyMachine.getCandy;
var count = candyMachine.status.count;

getCandy();
console.log(count);

//--(3) 구조분해할당
const {getCandy, status: {count}} = candyMachine;



  • 구조분해할당 - 배열
var array = ['Nodejs', {}, 10, true];
var node = array[0];
var object = array[1];
var boo1 = array[2];

console.log(node, obj, bool);

const [node2, obj2, , bool2] = array; //array리스트 요소를 분해해서 각 변수에 할당해줌
//10은 할당하지 않을거기때문에 빈칸으로 남겨두면 됨
console.log(node2, obj2, bool2);




6. 클래스

ES2015부터 프로토타입 문법을 깔끔하게 작성할 수 있는 Class 문법 도입

  • Class 내부에 관련된 코드들이 묶임
  • Super로 부모 Class 호출
  • Static 키워드로 클래스 메서드 생성
class Human {
    constructor(type = 'human') {
        this.type = type;
    }

    static isHuman(human) { //정적메서드
        return human instanceof Human;
    }

    breathe() { //인스턴스메서드
        console.log('h-a-a-m');
    }

}

class Zero extends Human {
    constructor(type, firstName, lastName) {
        super(type); //부모생성자 호출
        this.firstName = firstName;
        this.lastName = lastName;

    }

    sayName() { //인스턴스메서드
        super.breathe(); //부모의 breathe()메서드 호출
        console.log(`${this.firstName} ${this.lastName}`);

    }
}

//객체 생성
const newZero = new Zero('human', 'Zero', 'Cho');
newZero.sayName();
console.log(Human.isHuman(newZero)); // newZero가 Human객체이니?->상속했으니까 true



  • [참고] JS에서 ||연산자
    자바스크립트에서 논리연산자는 단순히 참과 거짓을 판단해주는 연산자가 아니라 연산에 사용된 피 연산자 중 하나를 반환해주는 연산자에 불과합니다.
    이 연산자는 → 방향으로 연산을 진행하고 가장 먼저 참(true) 의 형태를 가진 value 가 나오는 경우 그 피연산자를 바로 반환해버리고 연산을 끝내버립니다.
    (https://mynameisdabin.tistory.com/10)
var Human = function(type) {
  this.type = type || 'human';
  //인자에 아무런 값이 없으면 human이 할당됨.
};

7. 프로미스

7-1. 프로미스 체이닝

const condition = true;
const promise = new Promise((resolve, reject) => {
    if(condition) {
        resolve('성공');
    }else {
        reject('실패');
    }
})

//프로미스 체이닝
promise.then((message) => { //message로 '성공'이 전달됨.(위의 condition이 true인 경우)
    console.log(message);
    return new Promise((resolve, reject) => {
        resolve(message + 1);
       //reject(message + '실패');인 경우 출력결과: 성공 성공실패 finally
    })

}). then(message => { //message로 '성공1'이 전달됨
    console.log(message);
    return new Promise((resolve, reject) => {
        resolve(message + 2);
    })
}).then((message) => { //message로 '성공12'가 전달됨
    console.log(message);
}).catch((error) => {
    console.log(error);
}).finally(() => console.log('finally'));

//출력결과: 성공 \n 성공1 \n 성공12 \n finally




7-2. Promise.all()

//Promise.resolve() : resolve를 호출해주는 promise객체를 바로 만들어줌. test용 (위의 resolve와는 다른거임)
const promise1 = Promise.resolve('성공1'); 
const promise2 = Promise.resolve('성공2');

Promise.all([promise1, promise2]).then(result => console.log(result)).catch(error => console.log('error!'));
//Promise.all() : 모두 resolve()가 호출될 때까지 기다림
//promise1,2 두개가 모두 resolve함수가 호출되면 메시지가 result로 list로 들어오게 됨.




8. async/await

const promise3 = Promise.resolve('성공3');
const promise4 = Promise.resolve('성공4');
(async() => {
    for await (promise of [promise3, promise4]) { //resolve함수가 호출된 순서대로 각각 호출됨.
        console.log(promise);
    }
})(); //})까지는 함수를 정의만 한거기때문에 ()까지 붙여서 실행해줘야함.

좋은 웹페이지 즐겨찾기