javaScript

javaScript call() 메서드

mooyou 2023. 8. 8. 23:51
728x90
300x250
SMALL

call()

javaScript 함수의 내장 메서드 중 하나로, 다른 객체의 컨텍스트에서 함수를 호출하는 기능을 제공한다.

즉 call()메서드를 사용하면 함수를 호출하면서 함수 내부에서 사용되는 this값을 명시적으로 지정할 수 있다.

 

문법

functionName.call(thisArg, arg1, arg2, ...);
  • functionName : 호출하려는 함수의 이름
  • thisArg : 함수 내에서 this로 사용될 객체를 지정
  • arg1, arg2, ... : 호출하려는 함수에 전달할 인수들을 나열한다. 
var person = {
  name: "John",
  age: 30,
  greet: function() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
  }
};

var anotherPerson = {
  name: "Alice",
  age: 25
};

person.greet(); // Output: Hello, my name is John and I am 30 years old.

person.greet.call(anotherPerson); // Output: Hello, my name is Alice and I am 25 years old.

person.greet.call(anotherPerson);

person의 greet 메서드를 호출하면서 call메서드를 사용 anotherPerson객체를 this로 사용 결과 값이 다르게 나온다.

728x90
반응형
LIST