자바스크립트 호출 및 적용 101

자바스크립트 코드를 읽는 데 충분한 시간을 보냈다면 아마도 call 및 apply 를 보았을 것입니다. 저 같으면 금방 헷갈립니다. 걱정하지 마십시오. 이러한 방법은 이해하기 쉽습니다. 나는 당신이 모두 시작할 수 있도록 몇 가지 기본 사항을 다룰 것입니다!

나는 넘어갈 것이다:
  • 콜 이용방법
  • 이용방법 신청하기
  • 콜 사용시와 사용시 적용

  • 시작하기 전에 이 두 가지는 매우 유사하다는 점을 명심하십시오. 하나를 배우면 다른 하나를 이해할 수 있습니다.

    통화 사용



    객체와 함수가 있다고 가정합니다.

    const breakfastObj = {
      food: 'blueberry waffles',
      drink: 'orange juice'
    }
    
    function sayBreakfast(){
      console.log(`I had ${this.food} and ${this.drink} for breakfast`)
    }
    

    sayBreakfast() 를 호출하면 반환됩니다.

    sayBreakfast() // I had undefined and undefined for breakfast
    

    sayBreakfast()를 breakfastObj로 사용하여 this 함수를 "호출"하려면 다음을 수행하십시오.

    sayBreakfast.call(breakfastObj) // I had blueberry waffles and orange juice for breakfast
    

    this 가 정의되지 않은 경우 전역 개체를 참조합니다(브라우저에 있는 경우 전역 개체는 아마도 window 개체일 수 있음). 그래서 우리는 이것을 할 수 있습니다:

    window.food = 'French toast'
    window.drink = 'Apple juice'
    sayBreakfast() // ... French toast and Apple juice
    


    이는 다음과 동일합니다.

    sayBreakfast.call() // ... French toast and Apple juice
    


    호출은 두 번째, 세 번째, ...n번째 인수도 허용합니다. 이러한 인수는 함수의 인수로 사용됩니다. 명확히하기 위해 예를 살펴 보겠습니다.

    const lunchObj = {
      food: 'tacos',
      drink: 'water'
    }
    
    function sayLunch(location){
      console.log(`I had ${this.food} and ${this.drink} for lunch at ${location}`)
    }
    
    sayLunch.call(lunchObj, "Taco Bell") // I had tacos and water for lunch at Taco Bell
    


    흠, 타코는 좋은 것 같아요 🤤. 함수가 여러 인수를 허용하는 경우 해당 인수도 전달할 수 있습니다.

    function sayLunch(location, company, time){
      console.log(`I had ${this.food} and ${this.drink} for lunch at ${location} with ${company} in the ${time}`)
    }
    
    sayLunch.call(lunchObj, "Taco Bell", "Jon and Juan", "afternoon") // I had tacos and water for lunch at Taco Bell with Jon and Juan in the afternoon
    


    적용 사용


    apply 는 call 처럼 작동합니다. 유일한 차이점은 함수 인수를 받아들이는 방식입니다. apply 쉼표로 구분하는 대신 배열을 사용합니다. myFunction.apply(obj, [arg1, arg2, argn])
    이전 예제를 사용하지만 apply 다음과 같이 사용합니다.

    const lunchObj = {
      food: 'tacos',
      drink: 'water'
    }
    
    function sayLunch(location, company, time){
      console.log(`I had ${this.food} and ${this.drink} for lunch at ${location} with ${company} in the ${time}`)
    }
    
    sayLunch.apply(lunchObj, ["Taco Bell", "Jon and Juan", "afternoon"])
    


    ES6spread operator을 사용하여 apply 의 배열 인수를 활용할 수 있습니다.

    다음은 모질라 페이지의 뻔뻔한 복사-붙여넣기입니다.

    function sum(x, y, z) {
      return x + y + z;
    }
    
    const numbers = [1, 2, 3];
    
    console.log(sum(...numbers));
    // expected output: 6
    
    console.log(sum.apply(null, numbers));
    // expected output: 6
    

    call 및/또는 apply를 사용자 정의 함수가 아닌 내장 함수에 사용할 수 있음을 명심하십시오. 이 같은:

    const someArr = ["foo", "bar", "baz"];
    
    console.log.apply(null, someArr) // foo bar baz
    


    그리고 멋진 것을 얻고 새 인수를 someArr에 추가하려면 다음을 수행하십시오.

    console.log.apply(null, ['hello', ...someArr]) // hello foo bar baz
    


    호출을 기억하는 방법과 인수를 적용하는 방법



    첫 글자를 보는 것이 누구인지 기억하는 비법 (credit SO )

  • A -> 적용 -> 배열

  • C -> 쉼표 -> 전화

  • 우리는 단지 표면을 긁었을 뿐이지만, 이것은 당신의 지식을 더 고급에 적용하기에 충분할 것입니다(말장난 😎)!

    자료/더 읽기:


  • Using 'apply' to Emulate JavaScript's Upcoming Spread Operator

  • Function.prototype.call()
  • Function.prototype.apply()
  • What is the difference between call and apply?
  • Function.apply and Function.call in JavaScript
  • 좋은 웹페이지 즐겨찾기