this

  1. ๊ธฐ๋ณธ์€ window

์•„๋ฌด html ํŒŒ์ผ์—์„œ <script> ํƒœ๊ทธ ์—ด๊ณ 

console.log(this) ์ฐ์œผ๋ฉด window ๋‚˜์˜ด

index.html

<html>
    <script>
        console.log(this); //window
    </script>
</html>

๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ํ•จ์ˆ˜์•ˆ์—์„œ๋„ window

function test() {
    console.log(this); // window
}

Q. Window?

window๋Š” ๋ชจ๋“  ์ „์—ญ๋ณ€์ˆ˜, ํ•จ์ˆ˜ , DOM ์„ ๋ณด๊ด€ํ•˜๊ณ  ๊ด€๋ฆฌํ•˜๋Š” ์ „์—ญ๊ฐ์ฒด

์ „์ฒด๋ฅผ ๊ฐ์‹ธ๋Š” object ๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ํŽธํ•จ

  1. object ๋‚ด์— ํ•จ์ˆ˜์—์„œ๋Š” ๋ถ€๋ชจ object

var obj1 = {
    data : 'data',
    fun1 : function() {console.log(this)}
}


obj1.fun1(); //obj1์ด ์ถœ๋ ฅ๋œ๋‹ค.

object ๋‚ด์—์„œ์˜ this๋Š” ๋ถ€๋ชจ object๋ฅผ ๊ฐ€๋ฅดํ‚จ๋‹ค

์—ฌ๊ธฐ์„  obj1์ด ์ถœ๋ ฅ๋จ

var obj2 = {
    data : {
        fun2 : function() {console.log(this)}  
    }
}

obj2.data.fun2(); // this๋Š”obj2.data

์‚ฌ์‹ค 1๋ฒˆ๊ณผ 2๋ฒˆ์€ ๋™์ผํ•œ ์ด์•ผ๊ธฐ

<script>
    function fun1() {
        console.log(this);
    }
    
    window.fun1 = function() {
        console.log(this)
    }
    //์œ„ ์ฝ”๋“œ๋Š” ๋‘˜๋‹ค ๊ฐ™์€ ๋‚ด์šฉ์ž„
</script>

์šฐ๋ฆฌ๊ฐ€ ์•„๋ฌด ์„ ์–ธ์—†์ด ํ•จ์ˆ˜๋‚˜ ๋ณ€์ˆ˜ ๋งŒ๋“ค๋ฉด ๊ทธ๊ฑด ์ „๋ถ€ window ๊ฐ์ฒด์— ๋‹ด๊ธด๋‹ค.

  1. constructor ์•ˆ์—์„œ ์“ฐ๋ฉด constructor๋กœ ์ƒˆ๋กœ ์ƒ์„ฑ๋˜๋Š” object

function fun3() {
    this.name = 'Lee';
}

์—ฌ๊ธฐ์„œ this๋Š” fun3์œผ๋กœ๋ถ€ํ„ฐ ์ƒˆ๋กœ ์ƒ์„ฑ๋  object๋ฅผ ์˜๋ฏธํ•จ

var obj3 = new fun3();

console.log(obj3.name); //'Lee'๊ฐ€ ์ถœ๋ ฅ๋จ

  1. eventlistener ์•ˆ์—์„œ ์“ฐ๋ฉด e.currentTarget

Last updated