객체는 상태를 나타내는 프로퍼티와 동작을 나타내는 메서드를 하나의 논리적인 단위로 묶은 복합적인 자료구조이다.
동작을 나타내는 메서드는 자신이 속한 객체의 상태, 즉 프로퍼티를 참조하고 변경할 수 있어야 한다.
이때 메서드가 자신이 속한 객체의 프로퍼티를 참조하려면 먼저 자신이 속한 객체를 가리키는 식별자를 참조할 수 있어야 한다.
this는 함수가 호출되는 방식에 따라 바인딩 될 값, 즉 this 바인딩이 동적으로 결정된다.
this는 어디서든지 참조가 가능하다.
전역에서 this는 전역 객체 window를 가리킨다.
<script>
console.log(this); // window
function square(number){
console.log(this); // window
return number * number
}
square(2);
const person = {
name::"Lee",
getName(){
//메서드 내부에서 this는 메서드를 호출한 객체를 가리킨다.
console.log(this); // {name:"LEE",getName:f}
return this.name;
}
}
console.log(person.getName()); // Lee
function Person(name){
this.name = name;
//생성자 함수 내부에서 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
console.log(this)// Person {name:"Lee"}
}
const me =new Person("Lee")
</script>
this는 이렇듯 어느정도는 암기의 영역이다 .
그렇기 때문에 여러 코드를 분석하다보면 감이 조금씩 올 것이다.