하루에 3개씩 해보려고 합니다.
this에 대해 설명해주세요.(0428)
- 현재 실행되는 함수에서 참조하는 객체를 가리킴
메소에드에서 this는 해당 메소드를 호출한 객체를 가리킴
const person = {
name: "John",
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.sayHello(); // 출력: Hello, my name is John
생성자 this는 객체를 생성하는 생성자 함수 내에서 생성된 객체를 참조함
function Person(name, age) {
this.name = name;
this.age = age;
}
const john = new Person("John", 30);
console.log(john); // 출력: Person { name: 'John', age: 30 }
함수에서의 this는 일반적인 함수에서는 전역 객체롤 참조. use strict 모드를 사용하면 함수 내에서 undefined
를 반환
function sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
const person1 = {
name: "John",
sayHello: sayHello
};
const person2 = {
name: "Sarah",
sayHello: sayHello
};
sayHello(); // 출력: Hello, my name is undefined
person1.sayHello(); // 출력: Hello, my name is John
person2.sayHello(); // 출력: Hello, my name is Sarah