자바스크립트 클래스에서 객체의 메서드를 동적으로 호출하는 방법은 무엇인가요?
첫 번째로, 객체의 메서드를 변수로 할당하고 해당 변수를 호출하는 방법이 있습니다.
class MyClass {
method1() {
console.log("메서드 1을 호출했습니다.");
}
method2() {
console.log("메서드 2를 호출했습니다.");
}
}
const obj = new MyClass();
const dynamicMethod = obj.method1;
dynamicMethod(); // "메서드 1을 호출했습니다."
obj.method2 = dynamicMethod;
obj.method2(); // "메서드 1을 호출했습니다."
두 번째로, call
이나 apply
메서드를 사용하여 메서드를 호출하는 방법이 있습니다. 이 방법을 사용하면 컨텍스트를 지정할 수 있습니다.
class MyClass {
constructor(name) {
this.name = name;
}
greet() {
console.log(`안녕하세요, ${this.name}님!`);
}
}
const obj = new MyClass("John");
const dynamicMethod = obj.greet;
dynamicMethod.call(obj); // "안녕하세요, John님!"
마지막으로, ES6 이상에서 Proxy
를 사용하여 객체의 메서드 호출을 가로채고 처리할 수 있습니다. 이 방법은 더 고급적이며 복잡한 상황에서 유용합니다.
class MyClass {
method1() {
console.log("메서드 1을 호출했습니다.");
}
method2() {
console.log("메서드 2를 호출했습니다.");
}
}
const obj = new MyClass();
const handler = {
apply: function(target, thisArg, args) {
console.log("메서드 호출 중입니다.");
return Reflect.apply(...arguments);
}
};
const proxyObj = new Proxy(obj, handler);
proxyObj.method1(); // "메서드 호출 중입니다."와 함께 "메서드 1을 호출했습니다." 출력
이러한 방법을 사용하여 자바스크립트 클래스의 객체 메서드를 동적으로 호출할 수 있습니다.