this

this

this๋Š” ํ•จ์ˆ˜ ๋‚ด์—์„œ ํ•จ์ˆ˜ ํ˜ธ์ถœ ๋งฅ๋ฝ(context)๋ฅผ ์˜๋ฏธํ•œ๋‹ค. ๋งฅ๋ฝ์ด๋ผ๋Š” ๊ฒƒ์€ ์ƒํ™ฉ์— ๋”ฐ๋ผ์„œ ๋‹ฌ๋ผ์ง„๋‹ค๋Š” ์˜๋ฏธ์ธ๋ฐ ์ฆ‰ ํ•จ์ˆ˜๋ฅผ ์–ด๋–ป๊ฒŒ ํ˜ธ์ถœํ•˜๋Š๋ƒ์— ๋”ฐ๋ผ์„œ this๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋Œ€์ƒ์ด ๋‹ฌ๋ผ์ง„๋‹ค๋Š” ๋œป์ด๋‹ค.

ํ•จ์ˆ˜ํ˜ธ์ถœ

function func(){
    if(window === this){
        document.write("window === this");
    }
}
func(); //window === this

๋ฉ”์†Œ๋“œ์˜ ํ˜ธ์ถœ

var o = {
    func : function(){ //๋ฉ”์†Œ
        if(o === this){
            document.write("o === this");
        }
    }
}
o.func(); //o === this

๊ฐ์ฒด์˜ ์†Œ์†์ธ ๋ฉ”์†Œ๋“œ์˜ this๋Š” ๊ทธ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฅดํ‚จ๋‹ค.

์ƒ์„ฑ์ž์˜ ํ˜ธ์ถœ

var funcThis = null; 
 
function Func(){
    funcThis = this;
}
var o1 = Func();
if(funcThis === window){
    document.write('window <br />'); // window
}
 
var o2 = new Func();
if(funcThis === o2){
    document.write('o2 <br />'); // o2 
}
//this ์ƒ์„ฑ์ž๊ฐ€ ๋งŒ๋“  ๊ฐ์ฒด๋ฅผ ๊ฐ–๋Š”๋‹ค. 

apply, call

var o = {}
var p = {} 
function func(){ //switch : ๊ฐ’๊ณผ ๊ฐ™์€ ๊ฒƒ์„ ๋งŒ๋‚ฌ์„๋•Œ ๊ฒฐ๊ณผ๊ฐ’์ด ์ถœ๋ ฅ๋จ  break๋ฅผ ๋งŒ๋‚ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
    switch(this){
        case o:
            document.write('o<br />');
            break;
        case p:
            document.write('p<br />');
            break;
        case window:
            document.write('window<br />');
            break;          
    }
}
func(); //window 
func.apply(o); // o 
func.apply(p); // p

ํ•จ์ˆ˜์˜ ๋ฉ”์†Œ๋“œ์ธ apply, call์„ ์ด์šฉํ•˜๋ฉด this์˜ ๊ฐ’์„ ์ œ์–ดํ•  ์ˆ˜ ์žˆ๋‹ค.

๋ฉ”์†Œ๋“œ(๋…ธ์˜ˆ) ๋Š” ๊ฐ์ฒด(์ฃผ์ธ) ์— ์ข…์†๋˜์–ด ์žˆ๋‹ค. apply -> ์ด๋Ÿฌํ•œ๊ฒƒ์„ ์ œ์–ด ํ•  ์ˆ˜ ์žˆ๋‹ค.

Last updated