Notice
Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

HYEWON JUNG의 개발일지

일급 객체로서의 함수 본문

JavaScript

일급 객체로서의 함수

혜won 2023. 10. 26. 08:42

(1)변수에 함수를 할당할 수 있다. 

const sayhello = function(){
	console.log('hello');
}

장점

sayHello 란 이름을 가지고 어디서나 함수 호출을 할 수 있다. 

객체에 넣을 수도 있고 매개변수로 지정할 수도 있다.

=>함수가 마치 값으로 취급된다. // 함수가 나중에 쓰일 수 있도록 조치 되었다.

 

(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);// = function(x){return x + 5;}
	console.log(addFive(10))// = function(10){return 10 + 5;}

(4) 객체의 프로퍼티로 함수를 할당

const person = {
	name: hyewon,
    age : 24,
    isMarried : false,
    sayHello : function(){
    	console.log('hello my name is + this.name')//템플릿리터럴(`hello my name is ${this.name}`)
    }
}

person.sayHello(); // hello my name is john

=> 만약 함수를 화살표 함수로 작성한다면 this는 잡히지 않는다. 

 

(5) 배열의 요소로 함수를 할당

const myArray =[
	function(a, b){
    	return a+b
    }
    function(a, b){
    	return a-b
    }
]

console.log(myArray[0](2,3))//5
console.log(myArray[1](5,3))//2

=> 배열 내의 함수도 배열의 요소에 다가가는 방법과 동일하다. 

 

종합 예제

function multiplyBy(num){
	return function(x){
    	return x * num
    }
}

 function add(x, y){
 	return x * y
 }
 
 const multiplyByTwo = multiplyBy(2) //  function(x){return x * 2}
 const multiplyByThree = multiplyBy(3)// function(x){return x * 3}
 
 console.log(multiplyByTwo(10), multiplyByThree(10)) // 20, 30
 
 const result = add(multiplyByTwo(10), multiplyByThree(10))// 50
 
 console.log(result)