๐ JavaScript
๋ฅผ ์ฐ๋ ์ด์ : HTML
์ ์กฐ์ํ๊ธฐ ์ํด ์ฌ์ฉํ๋ค.
๐ 'use strict';
(strict mode)
this
Keyword<script>
console.log(this); // ์ฝ์์ฐฝ์ this ํค์๋ ์ถ๋ ฅ
function printThis (){
console.log(this);
}
printThis(); // ์ฝ์์ฐฝ์ this ํค์๋๋ฅผ ์ถ๋ ฅํ๋ ํจ์ ์คํ
</script>
โ๏ธ this ๊ฐ์ window{...} ๋ผ๊ณ ์ถ๋ ฅ๋๋ค. ์ฆ, ๋๋ฅผ ๋ด๊ณ ์๋ {object}๋ฅผ ์ถ๋ ฅํ๋ค.
๐ window
โ๏ธ strict mode
์์ ์ผ๋ฐ ํจ์ ๋ด์์ this๋ฅผ ์ถ๋ ฅ์ ์ฐ๋ฉด undefined
๊ฐ ์ถ๋ ฅ๋๋ค.
โ๏ธ ํจ์๋ ๋ณ์๋ฅผ <script></script>
์์ ์ ์ญ๊ณต๊ฐ์์ ๋ง๋ค๋ฉด {window}๋ผ๋ ์ ์ญ Object์ ๋ณด๊ด๋๋ค.
<script>
window: {
ํจ์ () {
console.log();
}
}
</script>
โ๏ธ Constructor(Object ์์ฑ ๊ธฐ๊ณ) ์์์ this
๋ฅผ ์ฌ์ฉํ๋ฉด instance(์๋ก ์์ฑ๋๋ object)๋ฅผ ๋ปํ๋ค.
<script>
function Machine(){ //constructor
this.name = 'kim';
}
var newObject = new Machine(); //new object, instance
</script>
โ๏ธ this๋ฅผ addEventListener ์์์ ์ฌ์ฉํ๋ฉด e.currentTarget์ ๋์ผํ๊ฒ ์ง๊ธ ์ด๋ฒคํธ๊ฐ ๋์ํ๋ ๊ณณ์ ๋ปํ๋ค.
<script>
document.getElementById('btn').addEventListener('click', function(e){
console.log(this); // id๊ฐ btn์ธ HTML
console.log(e.currentTarget); // ์์ ๋์ผํ ๊ฒฐ๊ณผ
})
</script>
๐ CASE 1 : EventListener ์์์ Callback ํจ์๋ฅผ ์ด๋ค๋ฉด this๋?
<script>
document.getElementById('btn').addEventListener('click', function(e){
var newArray = [1,2,3];
newArray.forEach(function(){
console.log(this);
});
});
</script>
ํจ์ ์์ ๋ค์ด๊ฐ๋ ํจ์๋ฅผ ์ฝ๋ฐฑํจ์๋ผ๊ณ ๋ถ๋ฅธ๋ค. ์ฆ, ํจ์ ์์์ ํ๋ผ๋ฏธํฐ ์ญํ ๋ก ๋ค์ด๊ฐ๋ ํจ์๋ฅผ ๋ปํ๋ค.
โ๏ธ forEach๋ผ๋ ํจ์ ์์ function(){} ์ฝ๋ฐฑํจ์๋ฅผ ๋ฃ์ด์ ์ฌ์ฉํ๋ค.
โ๏ธ ๊ฒฐ๊ณผ
Callback ํจ์๋ ๊ทธ๋ฅ ์ผ๋ฐ ํจ์์ ๊ฐ๊ธฐ ๋๋ฌธ์ {window} ๊ฐ์ฒด๊ฐ ์ถ๋ ฅ๋๋ค.
๐ CASE 2 : Object ์์์ Callback ํจ์๋ฅผ ์ด๋ค๋ฉด this๋?
<script>
var newObject = {
names : ['Kim', 'Lee', 'Park'];
printThis : function(){
newObject.names.forEach(function(){
console.log(this)
});
}
}
</script>
โ๏ธ ๊ฒฐ๊ณผ
forEachํจ์ ์์ Callback ํจ์๋ ๊ทธ๋ฅ ์ผ๋ฐ ํจ์์ ๊ฐ๊ธฐ ๋๋ฌธ์ {window} ๊ฐ์ฒด๊ฐ ์ถ๋ ฅ๋๋ค.
๐ CASE 3 : Object ์์์ Callback ํจ์๋ฅผ arrow function์ผ๋ก ์ด๋ค๋ฉด this๋?
<script>
var newObject = {
names : ['Kim', 'Lee', 'Park'];
printThis : function(){
console.log(this);
newObject.names.forEach(() => {
console.log(this)
});
}
}
</script>
โ๏ธ arrow function ํน์ง : ๋ด๋ถ์ this ๊ฐ์ ๋ณํ์ํค์ง ์๊ณ ์ธ๋ถ this ๊ฐ ๊ทธ๋๋ก ์ฌ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
โ๏ธ ๊ฒฐ๊ณผ
์์ ์ฝ๋์ this๊ฐ์ ๊ทธ๋๋ก ๋ฌผ๋ ค๋ฐ์์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ {names} ๊ฐ ์ถ๋ ฅ๋๋ค.
Arrow Function
๊ธฐ์กด ๋ฌธ๋ฒ : function() {} โ ์ ๋ฌธ๋ฒ : () => {}
โ๏ธ ์ ๋ฌธ๋ฒ์ ํน์ง์ this ๊ฐ์ ํจ์ ๋ฐ์ ์๋๊ฑธ ๊ทธ๋๋ก ์
โ๏ธ Object ๋ด this ์ถ๋ ฅํ๋ ๋ช
๋ น์ ํ๋ ํจ์๋ฅผ ์คํํ์ ๋, ๊ธฐ์กด๋ฌธ๋ฒ์์๋ ๊ทธ ํจ์๋ฅผ ํฌํจํ๊ณ ์๋ Object๊ฐ ์ถ๋ ฅ๋จ
โ๏ธ Object ๋ด this ์ถ๋ ฅํ๋ ๋ช
๋ น์ ํ๋ ํจ์๋ฅผ ์คํํ์ ๋, ์ ๋ฌธ๋ฒ์์๋ window{...} ๊ฐ ์ถ๋ ฅ๋จ