2012-11-30 2 views
0

HTML5 게임에 easeljs를 사용하고 있습니다.반환되는 이벤트 객체가 부모 객체를 덮어 씁니다. javacript, easeljs

클래스의 메서드 내에서 onClick을 호출하지만 이벤트 개체가 내 'this'개체를 덮어 쓰고 있으므로 더 이상 다른 클래스 메서드 나 vars에 액세스 할 수 없습니다. 이것은 지금 내가 이것을 실행하면

function Book(){ 

    this.text = "this is the text"; 

    this.makeText = function(){ 
      //Define some shapes 
      var character = new Container(); 
      character.addChild(some shapes); 
      character.onClick = this.detectClick; 
    } 

    this.detectClick = function(){ 
      alert(this.text); 
    } 
} 

그래서, 내가 때문에 내 detectClick 방법에 정의되지 않은 경고를 얻을 것입니다 : 예를 들어 나는 (분명히이 실제 코드, 그냥 빨리 그림 없음) 같은 것을 가지고 내 이벤트 개체.

그래서이 방법 내에서 원본 텍스트를 어떻게 호출합니까?

많은 감사는

답변

3

당신은 객체 참조

var self = this; 
character.onClick = function(){ self.detectClick() }; 
+0

완벽한 감사합니다. –

0

을 통과 또는 간단한 프록시 방법을 사용하는 우리 폐쇄해야합니다. 당신이 정말로 할 필요가 있음을 확인

function proxy(method, scope) { 
    return function() { 
     return method.apply(scope, params); 
    } 
} 
character.onclick = proxy(detectClick, this); 
0

는 범위 'this'

function Book(){ 

    this.text = "this is the text"; 

    this.makeText = function(){ 
      //Define some shapes 
      var character = new Container(); 
      character.addChild(some shapes); 
      character.onClick = this.detectClick.bind(this); 
    } 

    this.detectClick = function(){ 
      alert(this.text); 
    } 
} 
1

코드에서 문제입니다. 아래 코드와 같이 코드를 변경하십시오.

function Book(){ 

    this.text = "this is the text"; 
    var that=this; 
    this.makeText = function(){ 
     //Define some shapes 
     var character = new Container(); 
     character.addChild(some shapes); 
     character.onClick = that.detectClick; 
} 

this.detectClick = function(){ 
     alert(this.text); 
} 
} 
관련 문제