함수

uoayop·2021년 2월 27일
0

JavaScript

목록 보기
10/24
post-thumbnail

Javascript

함수 (function)

🔧 함수 만드는 방법

1. function 키워드를 사용해서 함수를 선언

function hello(name){
	return `hello ${name}`;
}
  • 백틱과 $을 사용해서 매개변수를 사용할 수 있다.

2. 함수를 변수처럼 대입해서 사용

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

console.log(hello);
  • 🧐 선언적 함수와 익명 함수를 만들어 변수에 할당하는 것의 차이점 ?
    • 선언적 함수 : 이름을 function 뒤에 붙여서 생성하는 것
      function hello(name) {}
    • 익명 함수 : 이름을 붙이지 않고, 변수에 할당하는 방식
      const hello = function() {}

hello();
hello2(); //error : hello2 is not function 
					//hello2가 뭔지는 알지만 함수인지는 모른다.

hello3(); //error : hello3 is not defined 
					//hello3 를 아예 찾을 수 없다.

//선언적 함수
function hello(){	
  console.log('hello')
}

//익명함수 : var 변수에 할당 , hoisting 가능
var hello2 = function(){
  console.log('hello');
}

//익명함수 : const 변수에 할당, hoisting 불가능
const hello3 = function(){
  console.log('hello3');
}

3. 생성자 함수로 함수 만들기

  • const hello = new Function(인자1, 인자2 , ... , 함수의 바디);
  • 함수도 어쨌든 객체다.
const sum = new Function('a','b','c','return a+b+c');
console.log(sum(1,2,3));
  • 🧐 function과 new function의 차이점 ?

    • new Function은 같은 범위에서 선언된 변수를 사용할 수 없다.
{
  const a = 1;

  const test = new Function('return a');

  console.log(test());
  // error: a is not defined
  // new function으로 선언된 함수가 같은 범위에 있는 지역변수에 접근이 안된다.
}

global.a = 0;
{
  const a = 1;
  
  const test = new Function('return a');
  
  console.log(test());
  // 출력 : 0
}

global.a = 0;
{
  const a = 1;
  
  const test = new Function('return a');
  
  console.log(test());
  // 출력 : 0
}
{
  const a = 2;
  
  const test = function() {
    return ;
  };
  
  console.log(test());
  // 출력 : 2
  // 같은 지역변수 a를 사용함
}

4. 화살표 함수 () => {}

  • ES6에서 나왔고, 간략하고 조금 더 보기좋은 형태로 표현 가능하다.
// 매개변수는 소괄호에 넣어서 전달한다.
// 함수의 바디는 중괄호에 정의한다.
const hello = () => {
  console.log('hello');
};

// 변수에 할당해서 쓸 수 있지만 항상 익명함수가 된다.
// 선언적 방식으론 쓸 수 없게된다.


//매개변수가 하나일 때, 괄호를 생략할 수 있다.
const hello2 = name => {
  console.log('hello2', name);
};


const hello3 = (name,age) => {
  console.log('hello3',name,age);
};

const hello4 = name => {
  return `hello ${name}`;
};

//!! return 도 생략 가능하다 !!
const hello5 = name => `hello ${name}`;

5. new 함수();

  • function을 이용해서 틀을 만들고, new를 이용해서 사용할 수 있는 객체들을 만든다.
// function Person이 여러 개의 객체를 만들 수 있는 이유 
// ✨ Person이라는 function이 자기 자신 객체를 가리키는 this를 만들어 내기 때문
// 🚨 arrow function 은 this를 만들지 않기 때문에, 이를 이용해서 객체를 만들 수 없다.

function Person(name,age){  
  console.log(this);
  // 출력 : Person {}
  this.name=name;
  this.age=age;
}

const p = new Person('doyeon',24);
console.log(p, p.name, p.age);
// 출력 : Person { name:'doyeon', age: 24} 'doyeon' 24

const a = new Person('woong',3);
console.log(a, a.name, a.age);
// 출력 : Person { name:'woong', age: 3} 'woong' 3

const Cat = (name,age) => {
  console.log(this);
  this.name = name;
  this.age = age;
  // error : Cat is not a constructor
  // 그 안에 this를 가지고 있지 않기 때문에 객체를 생성할 수 없다.
}

const c = new Cat('냥이',3);

6. 함수 안에서 함수를 만들어 리턴

  • 함수를 변수처럼 리턴할 수 있다.
function plus(base){
  return function(num){
    return base + num;
  }
}

const plus5 = plus(5);
// base : 5

console.log(plus5(10);)
// num : 10
// 출력 : 15

const plus7 = plus(7);
console.log(plus7(8));
// 출력 : 15

7. 함수를 인자로 하여 함수를 호출

function hello(c){
  console.log('hello');
  c();
}

hello(function(){
  console.log('콜백');
});

// 출력 : 
// hello
// 콜백
profile
slow and steady wins the race 🐢

0개의 댓글