๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/JavaScript

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] ์ผ๊ธ‰๊ฐ์ฒด(First Class Object)์— ๋Œ€ํ•ด์„œ ๊ฐ„๋žตํ•˜๊ฒŒ ์•Œ์•„๋ณด์ž

by YWTechIT 2021. 9. 3.
728x90

๐Ÿ“ ์ผ๊ธ‰๊ฐ์ฒด(First Class Object)์— ๋Œ€ํ•ด์„œ ๊ฐ„๋žตํ•˜๊ฒŒ ์•Œ์•„๋ณด์ž

ํ”„๋ก ํŠธ์—”๋“œ ์‹ ์ž… ๋ฉด์ ‘์—์„œ First Class Object๊ฐ€ ๋ฌด์—‡์ธ์ง€ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”.๋ผ๋Š” ์ฒซ ์งˆ๋ฌธ์„ ๋“ฃ๊ณ  ๋จธ๋ฆฌ๊ฐ€ ๋ฒ™์ช˜๋‹ค. ์šฉ์–ด๋ฅผ ๋“ค์–ด๋ดค์œผ๋ฉด ๊ด€๋ จ๋œ ๋‚ด์šฉ์„ ์ฅ์–ด์งœ๋‚ด๊ธฐ๋ผ๋„ ํ•  ํ…๋ฐ ๋„๋ฌด์ง€ ์ƒ๊ฐ์ด ๋‚˜์ง€ ์•Š์•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

๋‹ต๋‹ตํ•จ์„ ์ด๊ธฐ์ง€ ๋ชปํ•˜๊ณ  ๋ฉด์ ‘๊ด€๋ถ„๊ป˜ ์‹œ์›ํ•˜๊ฒŒ ๋ง์”€๋“œ๋ ธ๋‹ค. ๊ทธ๋Ÿฐ ์šฉ์–ด๋ฅผ ์ฒ˜์Œ ๋“ฃ์Šต๋‹ˆ๋‹ค.. ํ•œ๊ธ€๋กœ ์“ฐ์ด๋Š” ๋ง์ด ๋”ฐ๋กœ ์žˆ์Šต๋‹ˆ๊นŒ? ๊ณต๋ถ€๋ฅผ ๋” ํ•ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค.. ์ด์œฝ๊ณ  ๋ฉด์ ‘๊ด€๋‹˜์€ ์›ƒ์œผ๋ฉฐ ์ผ๊ธ‰ ๊ฐ์ฒด์— ๋Œ€ํ•ด ์ž์„ธํžˆ ์„ค๋ช…์„ ํ•ด์ฃผ์…จ๋‹ค. ๋งˆ์นจ๋‚ด ๋ฐ€๋ ค์˜ค๋Š” ์ž๊ดด๊ฐ..

 

 

๋น„๋ก ๋ฉด์ ‘์— ๋–จ์–ด์ง„ ์ด์œ ๊ฐ€ ์ผ๊ธ‰๊ฐ์ฒด๋ฅผ ๋ชฐ๋ผ์„œ ๋–จ์–ด์ง„ ๊ฒƒ์€ ์•„๋‹ˆ์ง€๋งŒ JS์˜ ๊ธฐ์ดˆ์ ์ธ ๋‚ด์šฉ์„ ๋งŽ์ด ๊ณต๋ถ€ํ•ด์•ผ๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์•Œ์•„๋ณด์ž ์ผ๊ธ‰๊ฐ์ฒด(First class object)๋ž€ ๋ฌด์—‡์ธ๊ฐ€?

 

MDN์—์„œ ์ฐพ์•„๋ณด๋‹ˆ๊นŒ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ •์˜๊ฐ€ ๋‚˜์˜จ๋‹ค. ํ•จ์ˆ˜๋ฅผ ๋ณ€์ˆ˜์ฒ˜๋Ÿผ ๋‹ค๋ฃจ๋Š” ์–ธ์–ด๋Š” ์ผ๊ธ‰ ํ•จ์ˆ˜๋ฅผ ๊ฐ€์กŒ๋‹ค๊ณ  ํ‘œํ˜„ํ•œ๋‹ค. ์ด ๋ฌธ์žฅ์„ ๋ณด๊ณ  ๋ฐ”๋กœ ํ•จ์ˆ˜ ํ‘œํ˜„์‹์ด ์ƒ๊ฐ๋‚ฌ๋‹ค. ํ•จ์ˆ˜ ํ‘œํ˜„์‹๊ณผ ํ•จ์ˆ˜ ์„ ์–ธ์‹์˜ ์ฐจ์ด๋Š” ์•ˆ๋‹ค๊ณ  ์šฐ์ญ๋Œ”์ง€๋งŒ ์ •์ž‘ ์ผ๊ธ‰๊ฐ์ฒด๋ฅผ ๋ชจ๋ฅด๋Š” ๋‚˜..

 

์ด์™ธ์—๋„ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ๋ฅผ ๋งŒ์กฑํ•˜๋ฉด ์ผ๊ธ‰ ๊ฐ์ฒด๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค. ์ฝ”๋“œ์™€ ํ•จ๊ป˜ ์‚ดํŽด๋ณด์ž.

728x90

1. Functions can be assigned to variables: ํ•จ์ˆ˜๋ฅผ ๋ณ€์ˆ˜์ฒ˜๋Ÿผ ์„ ์–ธํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€?

// 1
const sayMyName = function(name){
	console.log(name);
}

myName("Ted");
๐Ÿ‘‰๐Ÿฝ Ted

// 2
const sayMyName = (name) => {
	return name
}

console.log(sayMyName("Ted"));
๐Ÿ‘‰๐Ÿฝ Ted

 

2. Functions can be passed to arguments to other functions: ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ํ•จ์ˆ˜๋ฅผ ๋„ฃ์„ ์ˆ˜ ์žˆ๋Š”๊ฐ€?

const sayHelloToPerson = (greet, person) => {
	return greet() + " " + person
}

const sayGreet = function(){
	return "Hello,"
}

console.log(sayHelloToPerson(sayGreet, "Ted"));
๐Ÿ‘‰๐Ÿฝ Hello, Ted

 

3. Functions can be returned from other functions: ํ•จ์ˆ˜์˜ ๋ฆฌํ„ด ๊ฐ’์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉ ํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€?

const sayHello = function(){
    return function(greet){
        return greet
    }
}

const sayHelloOuter = sayHello();
const sayHelloInner = sayHelloOuter("Hello");
console.log(sayHelloInner)
๐Ÿ‘‰๐Ÿฝ Hello

// closure๋ฅผ ์‚ฌ์šฉํ•œ ๋ฐฉ๋ฒ•
const sayYouAndMe = function(yourName){
    return function(myName){
        return yourName + "๊ณผ " + myName;
    }
}

const sayYourName = sayYouAndMe("elon");
const sayMyName = sayYourName("Ted");
console.log(sayMyName);
๐Ÿ‘‰๐Ÿฝ elon๊ณผ Ted

 

reference

  1. MDN
  2. First Class Functions in JavaScript - Youtube
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€