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
Was this helpful?