📚 프론트엔드 공부 일지/JAVASCRIPT

JavaScript 함수

wei3on 2024. 6. 14. 15:49

 

  • 화살표 함수

() => vs function () {}

const double = function (x, y) {
  return x * 2
}
console.log('double: ', double(7))

const doubleArrow = x => x * 2
console.log('doubleArrow: ', doubleArrow(7))

const name = x => ({name: 'Heropy'})

 

  • 즉시 실행 함수

IIFE, Immediately-Invoked Function Expression

const a = 7
function double() {
  console.log(a * 2)
}
double();

(function () {
  console.log(a * 2)
})();

// 강사님은 이 방법 더 추천
(function () {
  console.log(a * 2)
}());

 

  • 호이스팅

함수 선언부가 유효범위 최상단으로 끌어올려지는 현상

const a = 7

double()

function double() {
  conso

 

  • 타이머 함수

setTimeout(함수, 시간) : 일정 시간 후 함수 실행

setInterval(함수, 시간) : 시간 간격마다 함수 실행

clearTimeout(함수, 시간) : 설정된 Timeout 함수를 종료

clearInterval(함수, 시간) : 설정된 Interval 함수를 종료

const timer = setTimeout(() => {
  console.log("Hi!")
}, 3000)

const h1El = document.querySelector("h1")
h1El.addEventListener('click', () => {
  clearTimeout(timer)
})

const timer2 = setInterval(()=> {
  console.log('hi')
}, 3000)

h1El.addEventListener('click',()=>{
  clearInterval(timer2)
})

 

  • 콜백(callback)

함수의 인수로 사용되는 함수

function timeout(callback) {
  setTimeout(() => {
    console.log('hi')
    callback()
  }, 3000)
}
//timeout 함수를 호출할때 하기의 인수를 하나 출력 
timeout(() => {
  console.log('done')
});

 

  • 생성자 함수(prototype)
const heropy = {
  firstname: 'heropy',
  lastname: 'park',
  getFullName: function () {
    return `${this.firstname} ${this.lastname}`
  }
}
console.log(heropy.getFullName())

const amy = {
  firstname: 'Amy',
  lastname: 'Clark',
  getFullName: function () {
    return `${this.firstname} ${this.lastname}`
  }
}
console.log(amy.getFullName())

const neo = {
  firstname: 'Neo',
  lastname: 'Smith',
  getFullName: function () {
    return `${this.firstname} ${this.lastname}`
  }
}
console.log(neo.getFullName())

 

이렇게 따로 객체데이터를 만들어서 각각 함수를 호출할 수도 있지만,

코드가 길어지면 효율적이지 못하기 때문에 다음과 생성자 함수로 코드를 변경할 수 있다.

function User(first, last) {
  this.firstName = first
  this.lastName = last
}
User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`
}

const heropy = new User('Heropy', 'Park')
const amy = new User('Amy', 'Clark')
const neo = new User('Neo', 'Smith')

console.log(heropy.getFullName()) //Heropy Park
console.log(amy.getFullName()) //Amy Clark
console.log(neo.getFullName()) //Neo Smith

 

  • this

일반(Normal) 함수는 호출 위치에 따라 this 정의!

화살표 (Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의!

const heropy = {
  name: 'Heropy',
  normal: function() {
    console.log(this.name)
  },
  arrow: () => {
    console.log(this.name)
  }
}

heropy.normal()
heropy.arrow()

const amy = {
  name: 'Amy',
  // 함수를 호출하는게 아니기 때문에 그냥 normal/arrow 함수 자체가 들어가는것
  normal: heropy.normal,
  arrow: heropy.arrow
}

amy.normal()
amy.arrow()

 

  • class 함수
function User(first, last) {
  this.firstName = first
  this.lastName = last
}
User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`
}

   ⬇️

class User {
  constructor(first, last) {
    this.firstName = first
    this.lastName = last
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

const heropy = new User('Heropy', 'Park')
console.log(heropy.getFullName())

'📚 프론트엔드 공부 일지 > JAVASCRIPT' 카테고리의 다른 글

JavaScript 상속. 확장  (0) 2024.06.14
JavaScript 조건문  (0) 2024.06.14
JavaScript 연산자  (0) 2024.06.14
JavaScript 함수 개념 정리  (1) 2024.06.03