this keyword
this
๋?
this
๋?
JS๋ OOP ์ธ์ด์ด๋ค
this
=> ๋ฌด์กฐ๊ฑด ์ด๋ค object๋ฅผ ์ง์นญ
method
=> ๊ฐ์ฒด ์์ ์ ์๋ ํจ์ ( .methodName() ์ผ๋ก ์คํํ๋ ํจ์)
function
=> method๊ฐ ์๋ ๋ชจ๋ ํจ์
function() {} ์ ์ ํ ๋, this ๊ฐ window๊ฐ ์๋ ๊ฒฝ์ฐ
method ์์ ths
โ -> ํด๋น method๊ฐ ์ ์๋ ๊ฐ์ฒด (object)
์์ฑ์ ํจ์ ์์ this
method ์ ์ ํ ๋, ๋ฐ๋์ function(){} ์ผ๋ก ์ ์ ํ๋ค!
ex)
const obj = {
name: 'obj',
method1: function(){
console.log(this) // this = obj
},
objInObj: {
name: 'oio',
oioMethod(){ // ES6 Syntatic sugar: ์ฝ๋๋ฅผ ์งง๊ณ ์ฝ๊ฒ ์ฐ๊ฒ ํด์ค! ํจ์๋ฅผ ์ด๋ ๊ฒ ์งง๊ฒ ์ ์ ํ๊ฒ ํด์ค!
console.log(this) // this = objInObj
}
},
arr: [0, 1, 2],
newArr: [],
method2 () {
/*
this.arr.forEach(
// ์ ๋ method๊ฐ ์๋๋ค! ๊ทธ๋ฅ ๋ด๊ฐ ๋ง๋ ์ต๋ช
ํจ์์
// -> this ์ฌ์ฉ ๋ถ๊ฐ
function(number){
this.newArr.push(number*100)
}.bind(this) // bindํด์ ์ฌ์ฉ ๊ฐ๋ฅํ๋ค!
// -> ๊ทธ๋ฐ๋ฐ ์ด๋ ๊ฒ ๊ธธ๊ฒ ์ธ๊ฑฐ๋...?
// => ๊ทธ๊ฒ ์ซ์ด์ ๋์จ๊ฒ arrow funciton์ด๋ค!
)//obj
*/
(number) => {
this.newArr.push(number * 100)
}
}
}
this
์๋ eventListener๊ฐ ๋ถ๋ฆฐ ์ฃผ์ด๊ฐ ๋๋ ์ ๊ฐ this
์ ๋ค์ด์จ๋ค!
์๋์ ์!
๋ถ๋ ค์ง ๋์์ ๋ฐ๋ผ ๋ฌ๋ผ์ง๋ค
Last updated
Was this helpful?