JavaScript
[JavaScript] this변경 bind, call, apply
힘없는염소
2023. 8. 7. 11:34
this를 다른 객체로 변경하려면 JavaScript의 bind, call, 또는 apply를 사용할 수 있습니다.
이러한 메서드들을 활용하여 함수 내부의 this를 원하는 객체로 명시적으로 바인딩할 수 있습니다.
- bind: 함수와 특정 객체를 묶어 새로운 함수를 생성합니다.
- call: 함수를 호출하는 동시에 특정 객체를 지정하여 this를 설정합니다.
- apply: 함수를 호출하는 동시에 특정 객체를 지정하여 this를 설정하며, 인자를 배열 형태로 전달합니다.
첫번째 인자는 this로서 사용될 Object 이다. 두 번째 인수 부터는 인자
fun.bind(thisArg, 인자, 인자, ...)
fun.call(thisArg, 인자, 인자, ...)
fun.apply(thisArg, 배열)
const myObject = {
name: "Alice",
};
function greet() {
console.log(`Hello, ${this.name}!`);
}
// bind를 사용하여 this를 myObject로 변경
const boundFunction = greet.bind(myObject);
boundFunction(); // Hello, Alice!
// call을 사용하여 this를 myObject로 변경
greet.call(myObject); // Hello, Alice!
// apply를 사용하여 this를 myObject로 변경
greet.apply(myObject); // Hello, Alice!
반응형