내가 작성한 꽤 큰 코드 본문에서 문제가 발생하여 다음과 같이 요약했습니다.
var Thing = function(argument){
this.property = argument;
this.obj = {
func: function(){
return this;
}
};
this.func = function(){
return this;
};
};
this.property
내부 에 액세스해야합니다 obj.func()
. 그러나의 가치는 this
내가 기대하는 것과 다릅니다.
> var thing = new Thing("value")
> thing.func()
Thing {property: "value", obj: Object, func: function}
> thing.obj.func()
Object {func: function}
나는 "일"을 호출라는 인스턴스를 인스턴스화 할 때 thing.func()
, this
현재의 인스턴스를 보유하고 Thing
예상대로. 하지만 내가 전화 thing.obj.func()
하면 thing.obj
. 무슨 일이야? 그 가치에 어떻게 접근합니까?
var thing = new Thing('value')
thing.obj.func() // this inside func will be the object before .func, which is thing.obj
한 가지 해결책은 함수를 객체에 바인딩하는 것입니다.
var Thing = function(argument){
this.property = argument;
this.obj = {
func: function(){
return this;
}.bind(this); // bind it to the current object
};
this.func = function(){
return this;
};
};
또는 다음의 개인 사본과 함께 클로저를 사용할 수 있습니다 this
.
var Thing = function(argument){
var that = this;
this.property = argument;
this.obj = {
func: function(){
return that;
}
};
this.func = function(){
return this;
};
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다