//var은 function 단위, let/const는 block 단위, const는 상수(constant)
function foo() {
let a = 1;
if(true) {
let a = 2;
console.log(a) // 2
}
console.log(a); // 1
}
let name = 'kim';
let age = 29;
function printInfo(name, age) {
const template = `Your name is ${name}. Your ${age} years old`;
return template;
}
console.log(printInfo(name,age));
// function 키워드 생략
const func1 function() {···};
const func1 = () => {···};
// 매개변수가 1개라면 괄호 생략 가능
const func2 = function(num) {···};
const func2 = num => {···};
// 함수 내부가 표현식 하나나면 중괄호와 return 생략 가능
const func3 = function(a,b) => { return a+b; };
const func3 = function(a,b) => a+b;
// new 키워드 사용 불가 = 생성자 함수를 만들 수 없음
const Cns = name => { this.name = name; };
const myCns = new Cns('foo'); // error
// arguments 객체가 바인딩 되지 않아서 나머지 매개변수 rest parameter 를 사용한다.
const printNumbers = (a, ...rest) = console.log(a, rest);
printNumbers(1,2,3,4); // 1, [ 2,3,4 ]
// this 를 새로 바인딩하지 않고 코드 바깥의 함수 또는 클래스의 this 를 사용
const obj = {
name: 'javscript',
const func = () => {
console.log(this.name); // javascript
}
}
// 클래스도 사실 함수라서 함수처럼 선언문과 표현식으로 정의 가능
// class 선언
class Person {···}
// class 표현식
const Person = class Person {···};
// 생성자 constructor (new로 호출시 자동 실행)
class Person {
constructor(name) {
this.name = name; // this는 생성된 인스턴스를 가리킴
}
}
// 상속 extends 과 super 키워드
class Animal {
constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name, color) {
super(name);
this.color = color;
}
}
// static 메서드(인스턴스 없이 호출 가능)
class Cat {
static roar() {
console.log('mew');
}
}
Cat.roar(); // mew
// js/main.js
export default {
sum(x,y) {
return x+y;
}
}
// app.js
import Main from './js/main.js'
console.log(Main.sum(1,2)); // 3;
// 1. Rest Operator
// 객체라면 나머지 프로퍼티를 묶어 객체로 반환
const object = {a: 1, b: 2 , c: 3};
const {a, b, ...objRest} = object;
console.log(a, b, objRest); // 1, 2 { c: 3 }
// 배열이라면 원소들을 묶어 배열로 반환
const array = [1,2,3,4,5];
const [c, d, ...arrayRest] = array;
console.log(c, b, arrayRest); // 1, 2
// 2. Spread Operator
const a = [1,2,3];
const aa = [...a, ...a];
console.log(aa) // [1, 2, 3, 1, 2, 3]
const {
abc,
def
} = Object;
// 위 아래 코드는 같은 의미
const abc = Object.abc;
const def = Object.def;
참고: https://ddalpange.github.io/2018/01/11/js-es6-three-dots/