자바스크립트에서 call(), apply(), bind()

안녕하세요!

새로운 자바스크립트 튜토리얼로 다시 돌아왔습니다. call() , bind()apply() - Javascript 영역에서 상당한 시간을 보낸 경우 이 세 가지 방법 중 적어도 하나를 보았을 것입니다. 글쎄, 당신은 일상 업무에서 자주 사용하지 않을 수도 있지만 Javascript 인터뷰에서 가장 자주 묻는 질문 중 하나입니다.

오늘은 그것들을 배우는 날입니다. 💪

Javascript에서 함수는 객체입니다. 개체는 속성과 메서드를 가질 수 있습니다. 따라서 모든 함수에는 이 세 가지 메서드가 있습니다.



하지만... 시작하기 전에 함수의 경우this를 다시 살펴보겠습니다. 저를 믿으세요, 그것이 게임의 80%입니다.

함수를 실행할 때 this는 함수가 호출되는 방식(런타임 바인딩)에 따라 결정됩니다.

const person = {
  firstName: 'Sanjeev',
  lastName: 'Sharma',
  age: 22,
  getIntro: function() {
     console.log(`${this.firstName} ${this.lastName} is ${this.age} years old.`);
  }
}

person.getIntro(); // "Sanjeev Sharma is 22 years old."

function randomFunc() {
  console.log(this);
}

randomFunc(); // window object


메서드에서: this는 소유자 개체를 나타냅니다.
함수에서(엉성한 모드): this는 전역 개체를 나타냅니다.
함수에서(엄격 모드): this가 정의되지 않았습니다.
this .article에 대한 충분한 지식입니다. 😉

전화()



MDN에 따르면:

The call() method calls a function with a given this value and arguments provided individually.



간단히 말해서 함수를 호출할 때 함수 내부에 무엇이 있을 것인지this 결정합니다.

아주 간단한 예를 들어 이해해 봅시다.

function personIntro() {
  console.log(`${this.firstName} ${this.lastName}`);
};

const person1 = {
  firstName: 'Sanjeev',
  lastName: 'Sharma'
};

personIntro(); // Output 1: undefined undefined

personIntro.call(person1); // Output 2: Sanjeev Sharma

personIntro.call({ firstName : 'Harry', lastName : 'Potter' }); // Output 3: Harry Potter

personIntro()와 콘솔thisfirstName에 액세스하려고 시도하는 기능lastName이 있습니다. 세 가지 출력이 있습니다.
  • call() 메서드를 사용하지 않았으므로 this는 기본적으로 window 개체를 참조합니다. window 개체에는 firstName 또는 lastName 와 같은 속성이 없습니다. 따라서 우리는 undefined undefined를 얻습니다.
  • 이번에는 call()를 사용하고 필요한 속성이 있는 개체를 전달합니다. this는 이제 person가 됩니다. 따라서 유리한 출력Sanjeev Sharma을 얻습니다.
  • 위와 동일하며 call()가 어떻게 작동하는지 증명하려고 합니다. 😝
  • call()에서 추가 인수를 전달할 수도 있습니다.

    function personIntro(city, state) {
      console.log(`${this.name} is from ${city}, ${state}`);
    };
    
    const person = {
      name: 'Max',
      age: 26
    }
    
    personIntro.call(person, 'Los Angeles', 'California'); // Output: Max is from Los Angeles, California
    


    따라서 call() 함수는 this 입니다. 👀

    묶다()



    MDN에 따르면:

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.



    한 번에 처리하기에는 정보가 너무 많습니다. 그러나 이제 우리는 call()를 이해하므로 그 지식을 사용하여 bind()를 이해합시다.

    function getPerson(person) {
      console.log(`${ person } is from ${ this.state }.`);
    }
    
    getPerson.call({ state : 'California' }, 'Max'); // Output 1: Max is from California.
    
    const personFromCalifornia = getPerson.bind({ state : 'California' });
    
    personFromCalifornia('Max'); // Output 2: Max is from California.
    personFromCalifornia('Ben'); // Output 3: Ben is from California.
    

    getPerson()에 접근하려는 함수this를 만들었습니다. 두 가지 출력이 있습니다.
  • call()를 사용하고 { state : 'California' }(첫 번째 인수)를 this로 전달합니다. 두 번째 인수는 person 입니다.
  • bind()를 사용하여 1과 동일한 출력을 얻으려고 합니다. bind()를 사용하여 this 값을 일부 함수에 바인딩하고 다른 함수를 반환받을 수 있습니다. 우리의 경우에는 { state : 'California' }로 바인딩하고 반환된 함수를 personFromCalifornia에 저장합니다. 이제 personFromCalifornia 를 호출할 때 person 인수를 전달하기만 하면 됩니다. 이미 this 값이 있습니다.
  • 다른 person 를 사용하여 동일한 함수를 다시 호출합니다.

  • 그렇다면 call()bind()의 차이점은 무엇입니까?
  • call()는 즉시 호출되는 반면 bind()는 나중에 호출할 수 있는 함수를 반환합니다.
  • call()는 추가 인수를 받지만 bind()는 그렇지 않습니다.
  • call()bind() 와 달리 함수의 복사본을 만들지 않습니다.

  • 휴! 거의 끝났습니다. 😪

    적용하다()



    MDN에 따르면:

    The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).


    call() 와 정확히 동일하지만 미묘한 차이가 있습니다.

    function sum(num1, num2) {
      console.log(this + num1 + num2);
    }
    
    sum.call(2, 3, 4); // Output: 9
    sum.apply(2, [3, 4]); // Output: 9
    

    call()는 개별적으로 인수를 취하지만 apply()는 인수를 배열로 취합니다. 😆 바로 그거야.

    끝. 🙌

    , GitHub 또는 에서 나와 연결하십시오.

    감사합니다. 👋 오늘 뭔가 배웠기를 바랍니다. 🙏

    좋은 웹페이지 즐겨찾기