📌 객체의 method
const boy = {
name: ‘Mike’,
sayName(){
// console.log(boy.name);
console.log(this.name);
}
}
boy.sayName()
let man = boy;
man.name = ‘Tom’;
console.log(man.name); // ‘Tom’
📌 객체의 this
예제 코드 1️⃣
let boy = {
name: ‘Mike’,
sayName(){
console.log(boy.name); // this를 사용하지 않고 객체에 직접 접근
// console.log(this.name);
}
let man = boy;
man.name = ‘Tim’;
boy = null; // boy는 null이 됨
man.sayName(); // TypeError: cannot read properties …
예제코드 2️⃣
let boy = {
name: ‘Mike’,
sayName(){
// console.log(boy.name);
console.log(this.name); // this를 사용함
}
}
let man = boy; // man에 객체를 할당
man.name = ‘Tim’; // man의 name을 Tim으로 변경
boy = null; // boy에 null을 할당
man.sayName(); // ‘Tim’
// man으로 객체에 접근 했을때 정상적으로 메서드 호출
📌 참고
- 화살표 함수로 메서드를 만들면 this는 전역객체를 호출한다
- 전역객체는 브라우저에선 window, node.js에선 global
- 가능하면 메서드에는 함수 선언문을 사용할 것
- 함수 표현식은 this 사용 못함!