5. Variables & Constants
var
let
const
값이 바뀌면
값이 바뀌지 않으면
* 호이스팅 주의
console.log(x);
var x = 'hello';
> undefined > Uncaught ReferenceError: x is not defined
console.log(x);
const x = 'hello';
console.log(x);
let x = 'hello';
7. Arrow Function Expression
const sum = (num1, num2) => {
return num1 + num2;
}
const sum = (num1, num2) => num1 + num2;
function sum (num1, num2) {
return num1 + num2;
}
const sum = function (num1, num2) {
return num1 + num2;
}
or
* 호이스팅 됨
* function을 완전히 대체하지는 않음. new 불가
함수의 몸체가 한 줄이면 중괄호 & return 생략
8. Arrow Function Expression
인자가 1개면 괄호 생략 가능 인자가 없으면 괄호 생략 불가
const log = text => {
console.log(text);
}
log('hello');
const log = () => {
console.log('hello');
}
log();
9. Arrow Function Expression
lexical this
> name is :
function runner (name) {
this.name = name;
setTimeout(function () {
console.log('name is : ', this.name);
}, 1000);
}
const newRunner = new runner('hello');
function runner (name) {
this.name = name;
setTimeout(() => {
console.log('name is : ' + this.name);
}, 1000);
}
const newRunner = new runner('hello');
> name is : hello
10. Template Literals
const name = 'Janghyun';
console.log('my name is ' + name);
console.log(`my name is ${name}`);
> my name is Janghyun
const address = 'korean'
+ 'seoul';
console.log(address);
const address = `korea
seoul`;
console.log(address);
> korea
seoul
=
12. forEach(), for-in, for-of
var arr = ['a', 'b', 'c'];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
arr.forEach(one => {
console.log(one);
});
for(let i in arr){
console.log(arr[i]);
}
for(let i of arr){
console.log(i);
}
> a
b
c
← break 불가
13. Parameter Default Value
function log (str) {
str = str || '(empty)';
console.log(str);
}
log();
function log (str = '(empty)') {
console.log(str);
}
log();
=
14. Rest Operator, Spread Operator
나머지 연산자
function log (){
var people = [].slice.call(arguments);
people.forEach(person => {
console.log(person);
});
}
log('Han', 'Kim', 'Lee'); // 개수 가변
function log (...people) {
people.forEach(person => {
console.log(person);
});
}
log('Han', 'Kim', 'Lee'); // 개수 가변
=
> Han
Kim
Lee
function log (one, two, ...rest) {
console.log(one);
console.log(two);
console.log(rest);
}
log(1, 2, 3, 4, 5);
> 1
2
[3, 4, 5]
16. Destructuring
객체 비구조화
function getStock(){
return {
symbol: "IBM",
price: 100.00
};
}
const { symbol, price } = getStock();
console.log(`${symbol} is $${price}`);
> IBM is $100
function getStock () {
return {
symbol : "IBM",
price : 100.00
};
}
const result = getStock();
const symbol = result.symbol;
const price = result.price;
console.log(`${symbol} is $${price}`);
=
17. Destructuring
배열 비구조화
> Kim
Han
> Kim
Han
["Lee", "Park"]
let [name1, name2] = ['Kim', 'Han'];
console.log(name1);
console.log(name2);
let [name1, name2, ...rest] = ['Kim', 'Han', 'Lee', 'Park'];
console.log(name1);
console.log(name2);
console.log(rest);
18. Class & Inheritance
> Child {familyName: "Han", firstName: "Janghyun"}
true
true
class Parent {
constructor (familyName) {
this.familyName = 'Han';
}
}
class Child extends Parent {
constructor (firstName, familyName) {
super(familyName);
this.firstName = firstName;
}
}
const me = new Child('Janghyun', 'Han');
console.log(me);
console.log(me instanceof Child);
console.log(me instanceof Parent);
사실은 prototype
19. Class getter & setter
> Person {}
> Person {_name: "Janghyun"}
class Person {
get name (){
return this._name;
}
set name (name){
this._name = name;
}
}
const person = new Person();
console.log(person);
person.name = 'Janghyun';
console.log(person);
무한루프 조심
20. Class getter & setter
함수 선언
const person = new Person();
person.walk();
person.sleep();
function Person () {
return {
walk : function () {
console.log('walking...');
},
sleep : function () {
console.log('sleeping...');
}
}
}
class Person {
walk () {
console.log('walking...');
}
sleep () {
console.log('sleeping...');
}
}
=
객체 리터럴에도 해당
22. Module – import & export
export & import { }
export default & import
export const number = 100;
import { number } from './test'
console.log(number);
export default const number = 100;
import number from './test'
console.log(number);
import { number as num } from './test'
console.log(num);
or
or
import num from './test'
console.log(num);
권장
27. Promise
new Promise()
Promise.resolve(), Promise.reject()와 다름
함수 실행 스택을 새로 시작
Promise를 지원하지 않는 비동기 함수 처리
Promise.resolve()
.then(() => {
setTimeout(() => {
console.log('in setTimeout()');
}, 1000);
})
.then(() => {
console.log('final then');
});
> final then
in setTimeout()
잘못된 방법
Promise.resolve().then(() => {
return new Promise(resolve => {
setTimeout(() => {
console.log('in setTimeout()');
resolve();
}, 1000);
})
}).then(() => {
console.log('final then');
});
> in setTimeout()
final then
32. Generator
그만 알아보자
next() 표준 아님
send() 표준 아님
close() 표준 아님
throw() 표준 아님
function* fibonacci() {
var a = yield 1;
yield a * 2;
}
var it = fibonacci();
console.log(it); // "Generator { }"
console.log(it.next()); // 1
console.log(it.send(10)); // 20
console.log(it.close()); // undefined
console.log(it.next()); // throws StopIteration (as the generator is now closed)
표준인 것
generator*
yield
yield*
35. Async & Await – ES7 Draft
await : 현재 구문을 멈추고 다른 Promise를 실행, 그 Promise 완료되면 다시 진행
function delayFnc (delay, number) {
console.log('delayFnc()', delay, number);
return new Promise(resolve => {
setTimeout(() => {
resolve(number);
}, delay);
});
}
async function add1 () {
var a = delayFnc(500, 10);
var b = delayFnc(1000, 5);
return await a + await b;
}
add1().then(sum => {
console.log(sum);
});
async function add2 () {
var a = await delayFnc(500, 10);
var b = await delayFnc(1000, 5);
return a + b;
}
add2().then(sum => {
console.log(sum);
});
병렬 처리 === Promise.all()
확인용 딜레이 함수
순차 처리
36. Async & Await – ES7 Draft
Async 는 Promise Wrapper!! 기존 Promise 로직도 호환
비동기 함수 랩핑에는 new Promise() 필요
.resolve()
.reject()
.then()
.catch()
.all()
async & return
async & throw
async & .then()
async & .catch()
async & await
=