-
[JS] 내가 몰랐던 ES6 최신문법Java Script & Type Script 2023. 7. 10. 11:41728x90
ES6의 큰 특징으로 유명한 것들 말고, 찐으로 내가 몰랐던 문법들이다.
나머지 매개변수
function func(a,b,c, ...args){ console.log(...args) } func(1,2,3) func(1,2,3,4,5,6,7) /// 매개변수로 더 많은 파라미터들이 들어올 수 있다는 의미
일급객체로서의 함수
// 1. 변수에 함수를 할당할 수 있다. -> 함수가 마치 값으로 취급, 함수가 나중에 사용될 수 있도록 조치가 되었다. const sayHello = function () { console.log("hello") }
// 2. 함수를 인자로 다른 함수에 전달할 수 있다. function callFunction(func) { func() // 매개변수로 전달받은 변수가 사실 함수다. } const sayHello = function () { console.log("Hello") } callFunction(sayHello)
- 콜백함수 : 매개변수로써 쓰이는 함수
- 고차함수 : 함수를 인자로 받거나 return 하는 함수
// 3.함수를 반환할 수 있다. function createAdder(num){ return function(x){ return x+num } } const addFive = createAdder(5); console.log(addFive(10)); // 15
// 4. 객체의 프로퍼티로 함수를 할당 const person = { name: "John", age: 31, isMarried: true, sayHello: function(){ console.log("Hello, I am" + this.name)} } person.sayHello() // Hello, I am John // 근데 여기서 만약에 화살표함수를 쓴다면, const person = { name: "John", age: 31, isMarried: true, sayHello: ()=> { console.log("Hello, I am" + this.name)} } person.sayHello() // Hello, I am undefined // 화살표함수는 This를 바인딩하지 않는다.
// 5. 배열의 요소로 함수를 할당 const myArr=[ function (a,b){ return a+b; }, function (a,b) { return a-b; } ] console.log(myArr[0](1,3)); // 1+3 이 실행되어 4가출력 console.log(myArr[1](10,7)); // 10-7 이 실행되어 3이 출력
function multiplyBy(num){ return function (x) { return x * num; }; } function add(x,y){ return x + y; } const multiplyByTwo = multiplyBy(2); // 를 풀어서 작성하면 const multiplyByTwo = function (x){ return x * 2; // multiplyBy함수의 num 파라미터에 2가 갈아끼워짐 } console.log(multiplyByTwo(10)); // 20 const result = add(multiplyByTwo(5), multiplyByTwo(10)); console.log(result); // 30
728x90'Java Script & Type Script' 카테고리의 다른 글
[클린코드] 추상화, 관심사의 분리,의존성주입 (Java script version) (0) 2023.07.27 [자료구조] Map과 Set (0) 2023.07.10 [React] Recoil 설정과 대표 기능 소개 (0) 2023.04.29 [React] 게시글 최신순 정렬 구현 useState & 쿼리스트링 ( useReducer써보기) (0) 2023.04.08 [Refactor] Gnims 코드 리팩토링 with Chat GPT (0) 2023.03.22