재우니의 블로그

 

javascript 에서 this 키워드는 기본적으로 전역 객체를 참조합니다. 

 

그래서 this.변수에 값을 할당하면 전역 객체에 할당이 됩니다. 그리고 기본적인 setTimeout 으로 호출하면 기본적으로 this 가 전역객체를 바라봅니다.

 

하지만 object 를 바라보게 this 를 조정할 수도 있는데 이때 bind, appy, call 함수로 object 를 넘기면 전역 객체가 아닌 object 의 객체를 바라봅니다.

this.luckshim = "window.luckshim";

var obj = {
	luckshim: "obj.luckshim"
};

document.writeln("1: " + this.luckshim); //window.luckshim

setTimeout(function () {
	document.writeln("2: " + this.luckshim); //obj.luckshim
}.bind(obj), 1000);

setTimeout(function () {
	document.writeln("3: " + this.luckshim); //window.luckshim
}, 1000);

 

 

 

아래 예제에서는 두개의 오브젝트를 만들고, callme 함수만 다르게 구현했는데요. callme : objLuckshim.callme 를 할당하면 callme 함수와 동일해 집니다. 동일한 함수 구문을 두번이상 기재하지 않고자 할때 사용하면 될듯 싶네요. 동일한 함수를 할당했으니 objAspdotnet.callme() 를 호출하면 objAspdotnet 함수의 item 의 값이 출력됩니다.

 

오브젝트를 파라미터 형태로 전송하여 this.item 을 가져오는 방법을 하기 위해 function callItem() 함수를 만들었습니다.

그냥 callItem() 함수를 호출하면 this.item 은 전역 객체인 "window item" 값을 출력하게 됩니다.

 

객체 안의 item 을 this 키워드로 가져오기 위해서는 위에서 말했듯이 bind, apply, call 함수를 통해 파라미터 전송을 하면 됩니다.

 

1) bind 함수는 별도의 변수에 할당한 다음 호출하는 방식임
2) apply, call 함수는 곧바로 오브젝트를 전달해서 해당 오브젝트의 item 값을 출력 함.

 

 

this.item = "window item";

var objLuckshim = {
    item: 'luckshim',
    callme: function () {
    	document.writeln(this.item);
    }
};

var objAspdotnet = {
    item: 'aspdotnet',
    subitem: 'subcallme',
    callme: objLuckshim.callme
};

objAspdotnet.callme(); //aspdotnet

function callItem() {
	document.writeln(this.item);
}


var bindSample = callItem.bind(objAspdotnet);

bindSample(); //aspdotnet
callItem.apply(objAspdotnet); //aspdotnet
callItem.call(objLuckshim); //luckshim
callItem(); //window item