this keyword

this ๋ž€?

JS๋Š” OOP ์–ธ์–ด์ด๋‹ค

this

=> ๋ฌด์กฐ๊ฑด ์–ด๋–ค object๋ฅผ ์ง€์นญ

method

=> ๊ฐ์ฒด ์•ˆ์— ์ •์˜๋œ ํ•จ์ˆ˜ ( .methodName() ์œผ๋กœ ์‹คํ–‰ํ•˜๋Š” ํ•จ์ˆ˜)

function

=> method๊ฐ€ ์•„๋‹Œ ๋ชจ๋“  ํ•จ์ˆ˜

function() {} ์ •์˜ ํ•  ๋•Œ, this ๊ฐ€ window๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ

  1. method ์•ˆ์˜ ths

โ€‹ -> ํ•ด๋‹น method๊ฐ€ ์ •์˜๋œ ๊ฐ์ฒด (object)

  1. ์ƒ์„ฑ์ž ํ•จ์ˆ˜ ์•ˆ์˜ 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