Javascript/vanilla
ES6 문법
서앶인
2024. 2. 28. 20:54
ES5와 달라진 ES6 문법
📌 기본 파라미터와 가변 파라미터
- 기본 파라미터
function addContact( name, mobile, home = "없음", address = "없음", email = "없음" ) {
let str = `name = ${name}, mobile = ${mobile}, home = ${home}, address = ${address}, email = ${email}`;
console.log(str);
}
addContact("홍길동", "010-1234-5678") // name = 홍길동, mobile = 010-1234-5678, home = 없음, address = 없음, email = 없음
addContact("이몽룡", "010-1234-5678", "031-123-4567", "서울시") // name = 홍길동, mobile = 010-1234-5678, home = 031-123-4567, address = 없음, email = 서울시
- 파라미터 기본값(default) 할당 가능
- 가변 파라미터
function foodReport (name, age, ...favoriteFoods) {
console.log(name + ", " + age);
console.log(favoriteFoods);
}
foodReport("이몽룡", 20, "짜장면", "탕수육", "치킨)
// 이몽룡, 20
// ["짜장면", "탕수육", "치킨"]
foodReport("홍길동", 16, "초밥")
// 홍길동, 16
// ["초밥"]
- 파라미터 앞 부분이 ...로 시작
- 여러 개의 파라미터 값을 배열로 받는다.
📌 화살표 함수
- 기존 함수 표현식에서 간결함 제공
- 함수를 정의하는 영역의 this를 그대로 전달받음
// 모두 같은 함수
const test1 = function (a, b) {
return a + b;
}
const test2 = function (a, b) => {
return a + b;
}
const test3 = (a, b) => a + b;
- test2 함수의 코드 구현부에 리턴문만 존재하는 경우는 test3와 같이 중괄호( {} )를 사용하지 않고 리턴값을 화살표 기호 뒤에 작성.
📌 자바스크립트의 this
- 화살표 함수와 전통적인 함수는 서로 다른 this 값이 바인딩 될 수 있음.
- 메서드, 함수가 호출될 때마다 현재 호출중인 메서드를 보유한 객체가 this로 연결.
만일 현재 호출 중인 메서드를 보유한 객체가 없다면 전역 객체(브라우저 환경에서는 window 객체)가 연결.
var obj = { result: 0 };
obj.add = function (x, y) {
this.result = x + y;
}
obj.add(3, 4);
console.log(obj);
-> 결과 : { result: 7 }
- 현재 호출중인 메서드( add )를 포함한 객체가 obj 이므로 this는 obj
var obj = { result: 0 };
obj.add = function (x, y) {
this.result = x + y;
}
var add2 = obj.add;
console.log(add2 === obj.add); // 결과 : true
add2(3,4);
console.log(obj); // 결과 : { result: 0 }
console.log(result); // 결과 : 7
- add2에 obj.add 함수를 할당했으므로 같은 메모리 주소 참조하는 동일 함수
- add2 메소드를 호출할 때, 해당 메소드를 포함하는 특정 객체가 없기 때문에 전역 객체가 this로 연결
=> 전역 변수 result에 7 할당
- 함수, 메서드를 호출할 때 직접 연결할 this를 지정하고 싶다면
- bind() : 지정한 객체를 this로 미리 연결한(binding) 새로운 함수를 리턴
- apply(), call() : 지정한 객체를 this로 연결한 후 함수를 직접 호출
var add = function (x, y) {
this.result = x + y;
}
var obj = {};
// apply()
add.apply(obj, [3, 4]);
// call()
add.call(obj, 3, 4);
// bind()
add = add.bind(obj);
add(3, 4)
- bind 메소드는 인자로 전달한 obj 객체를 this로 강제 지정하여 만든 새로운 함수 리턴하여 새로운 메모리 주소가 다시 add 변수에 할당되기 때문에 add(3, 4) 함수를 호출하여도 전역 객체가 아닌 obj객체를 this로 가짐.
📌 화살표 함수의 this
var obj = { result: 0 };
obj.add = function (x, y) {
function inner () {
this.result = x + y;
}
inner();
};
obj.add(3, 4);
console.log(obj); // 결과: { result: 0 }
console.log(result); // 결과: 7
- inner()가 호출될 때의 형태가 특정 객체의 메서드 형태가 아니므로 inner()의 this는 전역 객체
var obj = { result: 0 };
obj.add = function (x, y) {
function inner () {
this.result = x + y;
}
inner = inner.bind(obj); // inner.bind(this);
inner();
};
obj.add(3, 4);
console.log(obj); // 결과: { result: 7 }
- bind() 함수를 사용하여 obj 객체를 this로 가지는 새로운 함수를 리턴하여 inner() 함수 재정의
var obj = { result: 0 };
obj.add = function (x, y) {
const inner = () => {
this.result = x + y;
}
inner();
};
obj.add(3, 4);
console.log(obj); // 결과: { result: 7 }
- inner 함수를 화살표 함수로 수정
- 화살표 함수는 함수가 정의되는 유효 범위(scope)의 this를 자신의 유효범위 this로 연결
=> bind(), apply() 등의 함수를 굳이 사용하지 않아도 됨.
📌 Promise
- 비동기 처리를 위한 객체
const p = new Promise((resolve, reject) => {
// 비동기 작업 수행
// 이 내부에서 resolve(result)함수를 호출하면 then에 등록해둔 함수 호출
// reject(error)가 호출되거나 Error가 발생되면 catch에 등록해둔 함수 호출
})
p.then((result) => { ... })
.catch((error) => { ... })
- 시작 함수 : new Promise로 객체를 생성할 때 인자로 전달하는 함수. Promise 객체가 생성됨가 동시에 함수 실행.
- Promise Chain : then()을 체인처럼 엮어서 비동기 작업을 순차적으로 실행
new Promise((resolve, reject) => {
resolve("first!");
})
.then((msg) => {
console.log(msg); // first!
return "second";
})
.then((msg) => {
console.log(msg); // second
return "third";
})
.then((msg) => {
console.log(msg); // third
})
new Promise((resolve, reject) => {
resolve("first!");
})
.then((msg) => {
console.log(msg); // first!
throw new Error("## 에러!!")
return "second";
})
.then((msg) => {
console.log(msg);
return "third";
})
.then((msg) => {
console.log(msg);
})
.catch((error) => {
console.log("오류 발생 : " + error) // 오류 발생 : ## 에러!!
})
- Promise Chain에서 예외 처리는 catch()를 이용
- then() 내부에서 오류가 발생하면 그 이후에 등록된 catch() 중 가장 가까운 위치의 catch()에 등록된 함수 호출