2011-05-13 5 views
1

다음 코드 스 니펫이 있습니다. 나는 각각 안에 '이'에 접근 할 수 없기 때문에 혼란 스럽다.Class.create 내의 'each'에서 'this'에 액세스 할 수 없습니다.

사용 된 자바 스크립트 라이브러리는 프로토 타입입니다.

MyClass = Class.create({ 

    initialize : function(options) { 

    this.testmsg = 'Hi!'; 
    alert(this.testmsg); // Here it is 'Hi!' 

    var elements = $$('img'); 

    elements.each(function(element) { 
     alert(this.testmsg); // Here it is 'undefined', even though I bind 'this' 
    }).bind(this); 

    } 
}); 

내가 끔찍하게 잘못 일을 할 수도 있지만 난 그냥 그게 뭔지 알아낼 수 없습니다.

'class.create'를 사용하는 동안 어떻게 'testmsg'에 액세스 할 수 있습니까?

답변

2

XD ... 작은 (그러나 중요한) 실수를.

elements.each(function(element) { 
     alert(this.testmsg); // Here it is 'undefined', even though I bind 'this' 
    }.bind(this)); 

당신은 내부 기능,

는 행운이

+0

하하, 고마워! 이것은 제가 '끔찍한 잘못'한 것을 보여 주려고했던 대답입니다. – Sander

0

클로저가 가리키는 점은 jquery 객체라고 생각합니다.

솔루션은 varthis를 저장하는 것입니다 :

MyClass = Class.create({ 

    initialize : function(options) { 

    this.testmsg = 'Hi!'; 
    var that = this; 
    alert(this.testmsg); // Here it is 'Hi!' 

    var elements = $$('img'); 

    elements.each(function(element) { 
     alert(that.testmsg); // Here it is 'undefined', even though I bind 'this' 
    }).bind(that); 

    } 
}); 
+0

) 내가 폐쇄에 testmsg에 액세스 할 수있는 방법에도 관심이 .. – Sander

1

이 때문에 각 루프에서 요소에 대한 귀하의 경우이 referrs.

당신이 당신의 클래스 조금 변경하여이 문제를 해결할 수 있습니다 (테스트되지 않음) :

MyClass = function(){ 
    var that = this; 
    this.testmsg = 'Hi!'; 
    alert(this.testmsg); // Here it is 'Hi!' 

    elements.each(function(element) { 
     alert(that.testmsg); // Here it is 'Hi!' 
    }); 
} 
+0

흥미로운 기술뿐만 아니라, 감사합니다. – Sander

1

당신은 당신의 initialize 기능의 정상에 this을 참조하는 변수 self을 만들어이 문제를 해결할 수없는 각각의 기능을 결합해야합니다. 내가 프로토 타입이 아닌 jQuery를 사용하고

MyClass = Class.create({ 
    initialize : function(options) { 
     var self = this; // Create a reference to 'this' 

     this.testmsg = 'Hi!'; 

     elements.each(function(element) { 
      alert(self.testmsg); 
     }); 
    } 
}); 
관련 문제