this - 자신이 속한 객체 또는 생성할 인스턴스를 가르키는 자기 참조 변수이다.
console.log(this);
function test(){
console.log(this);
}
test();
아무것도 없는 상태의 this는 window 객체를 나타낸다.
let employee = {
name : "Lee", num : 224, serial: function(){
return this.num + this.name;
}
};
console.log(employee.serial());
오브젝트 안의 this는 오브젝트를 나타낸다. 즉, employee.num, employee.name과 같은 의미이다.
<button type = "button" onclick="this.style.color='green'">Check</button>
여기서의 this는 button을 의미한다.
<button type = "button" onclick="callFunction(this);">Check2</button>
<select onchange="changeNumber(this);">
<option number="1">1</option>
<option number="2">2</option>
<option number="3">3</option>
</select>
function callFunction(obj) {
console.log(obj);
}
function changeNumber(obj){
console.log(obj.value);
}
callFunction에서 this는 해당 코드를 반환한다.
changeNumber에서 this는 해당 코드를 반환하지만 .value를 붙여줌으로써 선택한 number를 출력한다.
'프로그래밍 > Java Script' 카테고리의 다른 글
Java Script - Default function parameter (0) | 2022.12.11 |
---|---|
Java Script - scope (0) | 2022.12.11 |
Java Script - 크롬 개발자 도구 Chrome (0) | 2022.12.09 |
Java Script - Window 객체 (0) | 2022.12.08 |
Java Script - Json (0) | 2022.12.08 |