다음과 같이 this
당신이 다음 방법 중 하나를 따를 수 '인 myObject'의 인스턴스를 개인 기능을 작성하고 액세스하려면 윈도우 객체
function anyFunc(){
alert(this); // window object
}
anyFunc();
var anyFunc2 = function(){
alert(this); // window object
}
anyFunc2();
될 것입니다
한
module = (function() {
var privateFunc = function() {
alert(this);
}
var myObject = {
publicMethod: function() {
privateFunc.apply(this); // or privateFunc.call(this);
}
};
return myObject;
}());
module.publicMethod();
두
module = (function() {
var _this; // proxy variable for instance
var privateFunc = function() {
alert(_this);
}
var myObject = {
publicMethod: function() {
privateFunc();
}
};
_this = myObject;
return myObject;
}());
module.publicMethod();
다음은 귀하의 문제에 대한 해결책입니다. 프로토 타입 기반 객체를 사용하는 것이 좋습니다.
편집 :
첫 번째 방법을 사용할 수 있습니다.여기 myObject
사실
는 privateFunc
같은 범위에 있고 직접 실제 시나리오는 다음과 같습니다 this
에 프록시를 사용할 수 있던 기능
var privateFunc = function() {
alert(myObject);
}
내에서 사용할 수 있습니다. call
도 사용할 수 있습니다.
Module = function() {
var _this; // proxy variable for instance
var privateFunc = function() {
alert(this + "," + _this);
}
this.publicMethod = function() {
privateFunc(); // alerts [object Window],[object Object]
privateFunc.call(this); // alerts [object Object],[object Object]
}
_this = this;
return this;
};
var module = new Module();
module.publicMethod();
FYI :'this'는 변수 범위와 관련이 없습니다. 함수의 호출 컨텍스트와 만 관련됩니다. 그 값은 함수가 호출되는 방법 *에 달려 있습니다. –
BTW, 이런 종류의 상황에서 "this"를 윈도우가 아닌 정의되지 않게하려면 "strict"를 사용할 수 있습니다. 이런 종류의 오류를보다 명확하게 표시하는 데 많은 도움이 될 수 있습니다. – hugomg