this
는 함수를 호출할 때 함수 내부에서 자신이 속한 객체를 가리키는데 사용된다.
this
의 기본 호출 방식은 전역 객체를 가리킨다. 전역 객체는 브라우저에서는 window
객체이며, Node.js에서는 global
객체이다.
암시적 호출의 경우, this
는 함수를 호출한 객체를 가리킨다. 예를 들어, 아래의 코드에서 myObject
객체의 method1
함수 내부에서 method2
함수를 호출할 때, method2
함수 내부에서의 this
는 myObject
객체를 가리킵니다.
const myObject = {
value: 123,
method1() {
console.log(this.value); // 123
this.method2();
},
method2() {
console.log(this.value); // 123
}
};
myObject.method1();
명시적 호출을 통해 this
값을 직접 지정할 수 있다.
const myObject = {
value: 123,
myFunction() {
console.log(this.value);
}
};
const myOtherObject = {
value: 456
};
myObject.myFunction.call(myOtherObject); // 456
call
메소드는 함수를 호출할 때, 첫 번째 인자로 전달한 객체를 this
값으로 지정하고, 두 번째 인자부터는 함수의 인자로 사용된다. apply
메소드도 call
과 비슷한 역할을 하지만, 인자를 전달할 때 배열 형태로 전달한다는 차이점이 있다.
bind
메소드는 call
과 비슷한 역할을 하지만, 함수를 호출하지 않고 this
값을 지정한 새로운 함수를 반환합니다.
const myObject = {
value: 123,
myFunction() {
console.log(this.value);
}
};
const myOtherObject = {
value: 456
};
const boundFunction = myObject.myFunction.bind(myOtherObject);
boundFunction(); // 456
new
를 사용한 호출은 생성자 함수 내부에서 사용된다. 생성자 함수는 new
키워드와 함께 호출되며, this
는 새로운 객체를 가리킨다. 이렇게 생성된 객체는 생성자 함수의 프로토타입 객체를 상속하며, 이를 통해 객체 간의 상속 관계를 구현할 수 있습니다.
예를 들어, 아래 코드에서 Person
생성자 함수는 name
과 age
라는 두 개의 인자를 받아 this.name
과 this.age
프로퍼티에 값을 할당한다. 이렇게 생성된 객체는 Person.prototype
객체를 상속하며, greet
메소드를 사용할 수 있다.
function Person(name, age) {
this.name = name;
this.age = age;
}
// 프로토타입을 통해 greet 에서 Person 인스턴스를 바라보도록 할 수 있음.
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);
person1.greet(); // Hello, my name is Alice and I am 25 years old.
person2.greet(); // Hello, my name is Bob and I am 30 years old.
new
를 사용한 호출은 생성자 함수와 함께 사용된다. 생성자 함수 내부에서 this
를 사용하여 새로운 객체를 생성하고, 이를 반환한다. 이렇게 생성된 객체는 생성자 함수의 프로토타입 객체를 상속하며, 이를 통해 객체 간의 상속 관계를 구현할 수 있다.