this
값을 확인하는 중입니다. 이것은 다음과 같은 방법으로 해결 : 그것을 해결하는 방법
myObject.something();//this in something is myObject
window.something();//this is window
button.onClick=function();//this when button is clicked is button
가 이미 주어, 그것은 두 번째 시간 제한은 closure 전달의 setTimeout
var test = function() {
var me = this;// set reference to this
this.sayAgain=function(){
console.log("Hi, I am "+me.toString());
}
}
test.prototype.toString=function(){
return "test";
}
test.prototype.say = function() {
console.log("Hi, I am "+this.toString());
}
var t = new test();
setTimeout(t.say,50);//=window passing functon without ref to this
setTimeout(function(){
t.say();
},150);//=test passing ref with function
setTimeout(t.sayAgain,200);//=test using me as the saved this context
를 사용하여 다음 예에서와 같이 콜백을 지나가는 일반적인 함정이다 setTimeout에 말 콜백을 수백 번 전달할 계획이지만 테스트 객체 인스턴스를 몇 개만 만들면 마지막 인스턴스 (sayAgain)의 구현이 약간 더 잘 수행됩니다.
이렇게하면 테스트 인스턴스를 만들 때 closure를 만들지 만 sayAgain을 콜백으로 전달할 때가 아니기 때문에 많은 테스트 인스턴스를 만들고 많은 경우 say
을 전달하지 않으면 this.me와 this.sayAgain을 함수 본문을 닫고 say
을 종료로 전달하십시오.
Function.prototype.bind을 사용할 수 있지만 IE < 8에서는 지원되지 않으며 t.say
을 사용하여 나의 예와 같이 클로저를 만들지 확실하지 않습니다.
출처
2013-07-08 01:38:00
HMR