2012-11-04 3 views
1

객체 지향을 사용하여 프로젝트의 스크립트 파일을 만들고 jQuery 및 Datatables와 같은 프레임 워크/위젯을 사용합니다.객체 지향 자바 스크립트 파일에 jQuery 사용

클래스에 생성 한 public 속성은 jQuery 코드에서 실행되는 함수의 내부 범위에서 액세스 할 수 없습니다. 여기

는 샘플입니다

function MyClass() { 
     this.MyProperty = ''; 
    } 

    MyClass.prototype.initialize = function() { 
      $(document).ready(function(){ 
      alert(this.MyProperty); // MyProperty is undefined at this point 
     } 
    }; 

어떻게이 문제를 해결할 수 있습니까? 이것은 클래스의 모든 구성원이 액세스 할 수있는 속성을 갖는 올바른 방법입니까?

+2

모든 것을 가지고 달성하기를 원하십니까? – gdoron

답변

4

저장 this :

function MyClass() { 
     this.MyProperty = ''; 
    } 

    MyClass.prototype.initialize = function() { 
      var that=this; 
      $(document).ready(function(){ 
      // in event handler regardless of jquery this points 
      // on element which fire event. here this === document, 
      alert(that.MyProperty); // MyProperty is defined at this point 
     } 
    }; 
+0

감사합니다. 정확히 내가 필요로하는 것. –

0

this이 클래스에 있지만 함수에서 document를 가리 키지 않기 때문이다.

function MyClass() { 
    this.MyProperty = ''; 
} 

MyClass.prototype.initialize = function() { 
    var myClassInstance=this; 
    $(document).ready(function(){ 
     alert(myClassInstance.MyProperty); // Will contain the property 
    }); 
} 
0

$.proxy이 도움을 줄 수

function MyClass() { 
    this.MyProperty = ''; 
} 

MyClass.prototype.initialize = function() { 
    $(document).ready($.proxy(function(){ 
     alert(this.MyProperty); 
    },this)); 
}; 
+0

이 방법도 효과가있었습니다. –

0

이가 좀 더 쉽게 다른 사람과 조금 다른,하지만, : 그것은 당신의 클래스를 가리키는 때, 그것이 가리키는 것을 저장할 필요 작업. "this"컨텍스트를 initialize() 함수 외부에 할당하는 논리를 유지합니다. 당신의 독특한 케이스가이 솔루션을 실행 불가능하게 만들지는 못했지만 어쨌든 공유 할 수있을 거라고 생각했습니다.

function MyClass() { 
    this.MyProperty = ''; 
    $(function(){ 
     this.initialize(); 
    }.call(this)); 
} 

MyClass.prototype.initialize = function() { 
    alert(this.MyProperty); 
} 
관련 문제