- 전역에서 쓰인 this : window 객체 리턴
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>this</title>
</head>
<body>
<script>
console.log(this);
("use strict");
function fnc1() {
console.log(this);
}
fuc1();
</script>
</body>
</html>
- Object의 메서드안에서 쓰인 this : 메서드를 담고 있는 객체 리턴
var item = {
name: "kim",
hi: function () {
console.log(this);
},
};
item.hi();
var item2 = {
data: {
hi: function () {
console.log(this);
},
},
};
item2.data.hi();
- 생성자에서 쓰인 this : 새로 생성된 Object
function People() {
(this.name = "lee"), (this.age = 50);
}
var obj1 = new People();
- 이벤트리스너 안에서 this : 이벤트가 동작하는 곳
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>this</title>
</head>
<body>
<button id="btn">클릭하세요</button>
<script>
document.querySelector("#btn").addEventListener("click", function (e) {
console.log(this);
console.log(e.currentTarget);
</script>
</body>
</html>
- 화살표 함수 안에서 this : 상위 this 값을 그대로 적용 ( 화살표 함수 안에서 this는 새롭게 정의되지 않는다 .)
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>this</title>
</head>
<body>
<button id="btn">클릭하세요</button>
<script>
document.querySelector("#btn").addEventListener("click", (e) => {
console.log(this);
console.log(e.currentTarget);
var arr1 = ["2020년", "2021년", "2022년"];
arr1.forEach(function (a, b, c) {
console.log("this : " + this);
console.log("a : " + a);
console.log("b : " + b);
console.log("c : " + c);
});
arr1.forEach((a) => {
console.log("this : " + this);
});
});
</script>
</body>
</html>