JavaScript
'this' ํค์๋์ ๋ค์ํ ์ฌ์ฉ
vividswan
2023. 2. 19. 14:16
'this' ํค์๋์ ๋ค์ํ ์ฌ์ฉ
- ๋ณธ์ธ์ ๋ด๊ณ ์๋ ์ค๋ธ์ ํธ๋ฅผ ํํ
- ํจ์๋ฅผ ํฌํจํ๊ณ ์๋ ์ค๋ธ์ ํธ (์ค๋ธ์ ํธ ๋ด ํจ์(๋ฉ์๋)์์ ์ฌ์ฉ, arrow function ์ผ ์ ํจ์๋ฐ์ ์๋ this๋ฅผ ๊ทธ๋๋ก ์ฌ์ฉ)
- window (์ ์ญ์ ์ ์ธ, ํจ์ ์์ ์ ์ธ(strict ๋ชจ๋์์ undefined)) -> ํจ์๋ ๋ณ์๋ฅผ ์ ์ญ ๊ณต๊ฐ์ ๋ง๋ค๋ฉด window(global object)์์ ๋ณด๊ดํ๊ธฐ ๋๋ฌธ
- constructor์์์ this ํค์๋
- ์๋ก ์์ฑ๋๋ object(instance)๋ฅผ ์๋ฏธ
- addEventListener์ function์์ ์ฌ์ฉ ์
- e.currentTarget ( e.currentTarget๋? ์ด๋ฒคํธ๊ฐ ๋์ํ๊ณ ์๋ HTML ์์ )
๋ณธ์ธ์ ๋ด๊ณ ์๋ ์ค๋ธ์ ํธ๋ฅผ ํํ
let data = {
testArray: [1, 2, 3],
testFunc: function () {
console.log(this); // data ์ค๋ธ์ ํธ๋ฅผ ์ถ๋ ฅ
data.testArray.forEach(function () {
console.log(this); // ์ค๋ธ์ ํธ์์ ์ ์ธ๋ this๊ฐ ์๋๋ฏ๋ก window ์ถ๋ ฅ
});
},
};
data.testFunc();
Object
Window
Window
Window
arrow function ์ผ ์?
let dataOfArrowFunc = {
testArrayOfArrowFunc: [1, 2, 3],
testFuncOfArrowFunc: function () {
console.log(this); // dataOfArrowFunc ์ค๋ธ์ ํธ๋ฅผ ์ถ๋ ฅ
dataOfArrowFunc.testArrayOfArrowFunc.forEach(() => {
console.log(this); // ์์์ this๋ฅผ ๊ฐ์ ธ์ค๋ฏ๋ก window๊ฐ ์๋ dataOfArrowFunc ์ค๋ธ์ ํธ๋ฅผ ์ถ๋ ฅ
});
},
};
dataOfArrowFunc.testFuncOfArrowFunc();
Object
Object
Object
Object
constructor์์์ this ํค์๋
function TestConstructor(name) {
this.name = name;
this.testFunction = function () {
console.log(this); // ์ธ์คํด์ค ์ถ๋ ฅ
console.log(this.name); // ์ธ์คํด์ค์ name ์ถ๋ ฅ
};
}
const testInstance = new TestConstructor("testName");
testInstance.testFunction();
TestConstructor
testName
addEventListener์ function์์ ์ฌ์ฉ ์
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<butto id="test">test button</butto>
</body>
</html>
<script>
document.getElementById("test").addEventListener("click", function (event) {
console.log(this); // event.currentTarget ์ถ๋ ฅ
console.log(event.currentTarget === this); // true ์ถ๋ ฅ
let testArray = [1, 2, 3];
testArray.forEach(function () {
console.log(this); // addEventListener์์ ์ ์ธ๋ this๊ฐ ์๋๋ฏ๋ก window ์ถ๋ ฅ
});
});
</script>
<butto id="test">test button</butto>
true
Window
Window
Window
event.currnetTarget vs event.target
event.currnetTarget๋ ์ด๋ฒคํธ ํธ๋ค๋ฌ๊ฐ ๋ถ์ฐฉ๋์ด ์๋ ์์, event.target์ ํด๋ผ์ด์ธํธ๊ฐ ํด๋ฆญํ ์์ (์์ ํฌํจ)