[JS] 함수

Local Gaji·2023년 5월 6일

JavaScript

목록 보기
3/18

1. 함수 선언과 표현

  • 선언 방식은 두 종류

function hello() {
  // 함수 선언문
}


const hello = function () {
  // 함수 표현식
}

호이스팅

  • 선언문 함수는 하단에서 선언되더라도 최상단에서 해석됨 (호출 아래에서 선언 가능)
  • 표현식 함수는 호이스팅되지 않음

반환

return 키워드가 없으면 undefined를 자동으로 반환 (무시 가능)

2. 매개변수 패턴

  • 매개변수 초기값 지정
function hello(a, b = 1) {
  return a + b
}

sum(7) // 7 + 1 = 8
  • 객체 구조 분해 할당
const user = {
  name: 'gaji',
  city: 'busan'
}

function getName(user) {
  const { name } = user
  return name
}

function getName({ name }) {
  return name
}

console.log(getName(user))   // gaji

function getMail({ email = '이메일이 없습니다' }) {
  return email
}
  • 배열 구조 분해 할당
numbers = [1, 2, 3]

function getSecond([, b]) {
  return b
}

console.log(getSecond(numbers))   // 2
  • 나머지 매개변수 : 매개변수의 양을 예상할 수 없을 때, 전개 연산자를 사용
    • 매개변수들을 배열로 만들어줌
// 배열 속 요소의 합 구하기

function sum(...rest) {
  return rest.reduce(function (acc, cur) {
    return acc + cur
  }, 0)
}

// reduce : 콜백함수
// rest.reduce : rest 요소 개수만큼 콜백함수를 실행
// acc : 누적되는 값 (시작값 0으로 지정)
// cur : 현재 값 (요소의 값)
  • arguments : 함수를 호출할 때 사용한 매개변수들을 배열 형태 (유사 배열)로 저장한 객체
    • 나머지 매개변수를 사용하지 않고, 함수 내부에서 사용 가능
    • index와 length 메서드 외에 사용할 수 없음
function sum(...rest) {
  console.log(arguments)
}

3. 화살표 함수

const funcName = () => {}

  • 함수 선언, 표현 외 함수를 생성하는 방법
  • 중괄호 생략 가능, return 생략 가능
    • return 외 다른 로직이 포함되어있을 경우 생략 불가
  • 매개변수가 1개일 경우 소괄호 생략 가능
const a = (x,y) => {return x + y}
const b = (x,y) => x + y
// return 생략
const c = x => x * x
// 매개변수가 1개 : 소괄호 생략
const d = () => ({a: 1})  
// 객체 데이터 반환 시 소괄호를 사용하여 함수 블록이 아닌 객체 데이터임을 구분
const d = () => [1,2,3]
// 배열 데이터 반환

4. 즉시실행함수(IIFE)

정의되자마자 즉시 실행되는 함수

// 세미콜론을 앞에 붙여주기

;(() => {})()        // (F)()
;(function () {})()  // (F)()
;(function () {}())  // (F())
;!function () {}()   // !F()
;+function () {}()   // +F()


;((a, b) => {
  console.log(a.innerWidth)
  console.log(b.body)
})(window, document) // 코드의 난독화

5. 콜백

  • 함수에 매개변수로 들어가는 함수
  • 용도 : 함수를 순차적으로 실행하고 싶을 때
// 1을 출력하는 함수 바로 다음 2를 출력하는 함수를 실행하고 싶을 때
const first = (파라미터) => {
  console.log(1)
  파라미터()
}

const second = () => {
  console.log(2)
}

first(second)
  • 예시 1) 6보다 긴 문자열만 출력
longWords = words.filter(element => element.length > 6)
consloe.log(longWords)
// true 또는 false를 리턴하는 익명함수가 콜백함수로 사용됨
// callback (element) => {return element.length > 6}

https://www.youtube.com/watch?v=TAyLeIj1hMc


  • 예시 2) 1초 기다렸다가 1 + 2 계산 출력
const sum = (a, b, callback) => {
  setTimeout(() => {callback(a + b)}, 1000)
  // console.log(값)를 실행시키라는거
}

sum(1, 2, (value) => {console.log(value)})  
// (value) => {console.log(value)} 익명함수가 3번째 매개변수callback 으로 들어감

  • 예시 3) url의 이미지를 로드해서 출력
const loadImage = (url, callback) => {
  const imgEl = document.createElement('img')
  // img 태그를 생성하는 함수
  
  imgEl.src = url  
  // img 태그의 src 속성에 url을 할당
  
  imgEl.addEventListener('load', () => {
  // load : html 문서를 완전히 불러왔을 때 이벤트 발생
  // load 이벤트가 발생하면 callback함수를 실행함
    callback(imgEl) 
  })
}

loadImage('https://url', imgEl => {
  containerEl.innerHTML = ''
  containerEl.append(imgEl)
})

6. 호출 스케줄링

  • setTimeout 함수 : 특정 함수의 실행을 지연시키는 메서드
  • setTimeout(callback, t) : callback 함수를 t ms 이후에 실행
const hello = () => {
  console.log('hello')
}

setTimeout(hello, 2000)
  • clearTimeout : setTimeout을 취소시키는 메서드
const timeout = setTimeout(hello, 2000)
clearTimeout(timeout)
  • 예시) h1 요소를 클릭했을 때 타이머 초기화

const timeout = setTimeout(hello, 2000)

const h1El = document.querySelector('h1')

// click 이벤트가 발생한다면 콜백함수를 실행
h1El.addEventListener('click', () => {
  // hello 함수가 실행되기 전이라면, 실행되지 않도록 함
  clearTimeout(timeout)
})
  • setInterval(callback, t) : t밀리초 마다 callback 함수를 실행

  • clearInterval : setInterval 반복 실행을 종료시키는 메서드


추가1. 함수 vs 메서드

https://developer-talk.tistory.com/534

  • 일반함수 : 호출하는 객체가 없는 경우
  • 메서드 : 호출하는 객체가 있는 경우
const object = {
  show1: function() {
    console.log('메서드 호출')
  }
}

show2() => {
  console.log('함수 호출')
}

object.show1()  // 메서드 (객체를 통해 호출함)
show2()         // 함수
window.show2()  // 전역 객체를 통해 호출 가능
  • show1() 함수는 객체 object의 property
    • property: 객체 안에 선언된 이름과 값으로 이루어진 한 쌍
  • show2() 함수는 전역 객체 window의 property
    • 사용자가 정의한 객체가 아니므로 메서드가 아님

추가2. this

(출처 : https://nykim.work/71)

함수에서의 this

함수는 Window 객체의 property 이므로,
this는 Window 객체를 가리킴

const user = () => {
  return this
}
console.log(user())  // Window 객체 출력


var num = 0;

function Num() {
  this.num = 100;
  console.log(num)         // 100
  console.log(this.num)    // 100
  console.log(window.num)  // 100
}

// num은 전역 변수를 가리키게 됨

메서드에서의 this


const user = {
  firstName: 'local',
  lastName: 'gaji',
  fullName: function() {
    return `${this.firstName} ${this.lastName}`
    // this 가 user 객체를 가리킴
  }
}

user.fullName() // local gaji

메서드에서 this는 해당 메서드를 호출한 객체를 가리킴

이벤트 핸들러에서 this

const btn = document.querySelector('#btn')
// 버튼 찾기

btn.addEventListener('click', function() {
  console.log(this) // #btn 
}

this 는 이벤트를 받는 HTML 요소를 가리킴

화살표 함수에서 this

화살표 함수에서는 this를 새로 정의하지 않고, 바깥 함수의 this를 사용

7. this

  • 함수 안에서 사용되는 변수
  • 상황에 따라 this가 가리키는 대상이 달라짐
const timer = {
  title: "TIMER",
  timeout: function () {
    console.log(this.title)    // this = timer 객체
    
    setTimeout(function () {
      console.log(this.title)  // this = window 객체 
    }, 100)
  }
}

timer.timeout() // TIMER undefined 

setTimeout은 일반함수이므로 this.title는 window.title (undefined)

const timer = {
  title: "TIMER",
  timeout: function () {
    console.log(this.title)    // this = timer 객체
    
    setTimeout( () => {
      console.log(this.title)  // this = timer 객체 
    }, 100)
  }
}
timer.timeout() // TIMER TIMER

setTimeout이 화살표함수이므로 바깥함수의 this인 timer 객체를 가리킴

0개의 댓글