안녕하세요 저는 싱글 톤 자바 스크립트 디자인 패턴을 사용하기 시작했지만 일부 범위 문제가 있습니다. 여기에 저는 작은 아약스로 실험하고 있습니다. 싱글 톤을 검색하고 저장합니다. 싱글 톤의 함수에서 다른 함수 (this.ready, Ajax가 데이터를 검색하고 저장할 때 호출 됨)가 있지만이 "singleton"을 참조하지 않고 "Object # XMLHttpRequest "크롬 디버거에 따르면 파이어 폭스는 정의되지 않았다고 말합니다. 내가 대신 전역 변수를 사용하는 상단에서 단일 변수로()을 getHTTPObject를 선언하려고하면"this"로 javascript singleton 범위 문제
var mag = {
magObj: [], // object to store the retrieved json data
getData: function(){
request = getHTTPObject(), // defined externally
request.onreadystatechange = this.setData;
request.open("POST", "be.php", true);
request.send(null);
},
setData: function(){
if (request.readyState == 4)
{
this.magObj = JSON.parse(request.responseText);
this.ready(); // this line yields the error, seems "this" does not refer to the singleton
}
else if (request.readyState == 1)
{
}
},
ready: function() {
console.log('ready');
},
construct: function(){
this.getData();
},
}
또한 내가 정의되지 않은의 특성 'readyState가'를 읽을 수 없습니다 오류 를 얻을. 다시 것 같다 "이"getHTTPObject 내가 상단으로 설정에도 불구하고 정의되지 않은 수의 :
var mag = {
magObj: [],
request: getHTTPObject(),
getData: function(){
this.request.onreadystatechange = this.setData;
this.request.open("POST", "be.php", true);
this.request.send(null);
},
setData: function(){
if (this.request.readyState == 4) // debugger says this.request is undefined
{
this.magObj = JSON.parse(this.request.responseText);
}
else if (this.request.readyState == 1)
{
}
},
construct: function(){
this.getData();
},
}
자바 스크립트에서 "this"가 호출 함수에 따라 변경됩니다. 이 답변을 확인하십시오. http://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript – David