2011-04-30 10 views
1

제목을 사용하면 다음과 같은 오류가 발생합니다.이 시나리오에서 test.elem이 정의되지 않은 이유는 무엇입니까?

var test = { 

    elem : undefined, 

    init : function() { console.log("test.init() fired"); 

     elem = $("#id"); 
     console.log("elem assigned to jQuery object"); 

     elem.click(function() { console.log("elem clicked"); }); 
     console.log("elem click handler created"); 

    } 

}; 

test.init(); 
test.elem.click(); 

이해가 안됩니다. test.init()를 실행하여 test.elem의 값을 할당하면 나중에 액세스하려고 할 때 정의되지 않은 이유는 무엇입니까?

+1

'this.elem = $ ("# id를") '등 – mVChr

+0

을 난 그런 백치. 10 시간이 지나면 작업을 마칠 때가되었습니다. –

답변

3

test.elem을 참조하는 대신 init 함수 내에 'elem'이라는 새 참조를 만듭니다. 그것을 읽을 것이다 있도록, 'this.elem'에 요소를 할당해야합니다 init을 내부

:

init : function() { 
    console.log("test.init() fired"); 

    this.elem = $("#id"); 

    console.log("elem assigned to jQuery object"); 

    this.elem.click(function() { 
     console.log("elem clicked"); 
    }); 

    console.log("elem click handler created"); 
} 
+0

그래, 나는 완전히 놀았다. 나는 그 곳의 모든 곳을 교정했지만,이 한 자리를 잊어 버렸습니다. 나는 너무 오랫동안 일해왔다. 눈의 두 번째 쌍을 가져 주셔서 감사합니다! –

관련 문제