let sum = (a, b) => a + b; //a, b란 인수를 받아서 => a+b를 리턴하겠다
const adder = function (x) {
return function (y) {
return x + y;
}
}
const add5 = adder(5);
add5(7) //adder(5)(7)
const tagMaker = tag => content => `<${tag}>${content}</${tag}>``
// tag, content란 인수로 이걸 리턴하겠다
const divMaker = tagMaker('div');
divmaker ('hello') // '<div>hello</div>'
- 클로저 모듈 패턴
- 되도록 변수가 안쪽함수에 있으면 그거 쓰고, 없으면 바깥에 있는 변수를 참조함.
모듈화
const makeCounter = () => {
let value = 0;
return {
increase: () => {
value = value + 1
},
decrease: () => {
value = value - 1
},
getValue : () => value
}
}
const counter1 = makeCounter();
counter1.increase // +!
const counter2 = makeCounter();
counter1.decrease // -1
- 클로저를 이용해 내부함수를 객체에 담아 여러개의 내부함수를 리턴
- 변수 counter1은 객체다. 세개의 매서드를 포함한다.
- value값에 접근불가. 함수가 value값을 보존해서 side effect를 방지
- makeCounter로 리턴된 객체는 value값을 각자 독립적으로 갖게됨. 값이 보존됨.
- 모듈화 : 함수 재사용성을 극대화, 함수하나를 완전히 독립적인 부품으로 분리하는것
let x = 10;
function outer () {
x = 20; //전역변수임
function inner () {
let x
x = x + 20; //안쪽함수는 바깥 스코프에 아무영향 안미침
return x;
}
inner();
}
outer();
let result = x; //20
ES6 주요문법
- spread 문법 : 주로 배열을 풀어서 인자로 전달, 배열을 풀어서 각각의 요소로 넣을때 씀
- spread 문법은 기존배열을 펼쳐서 전달하므로 배열의 형태는 아님 [...arr]이렇게 넣어줘야 배열됨
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers) // 6
- rest 문법 : 파라미터를 배열형태로 받아쓸수 있음
- function sum(...Args){}
let arr = [1, 2, 3];
let arr2 = [...arr]; // arr.slice() 와 유사
arr2.push(4); // 참고: spread 문법은 기존 배열을 변경하지 않으므로(immutable), arr2를 수정한다고, arr이 바뀌지 않습니다.
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 }; //foo : baz로 바뀜
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six"); // 3,4,5,6 다 manyMoreArgs
구조분배할당
- 객체에서 구조분해할당을 사용하는 경우 선언없이 할당하면 에러가 발생할 수 있음.
const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
- 유튜버 개발자채용자 인터뷰 이오, 코딩애플, 니콜라스
- 인강사이트 유데미