2012-06-30 6 views
0

저는 자바 스크립트를 처음 사용하고 모범 사례를 배우려고합니다. 다음 코드에서 ctx 참조에 액세스 할 수없는 이유는 확실하지 않습니다. 로그는 myApp.init()에서 context2d 참조를 출력합니다. myApp 모듈의 return 문에 개인 객체 변수를 표시 할 수 있습니까? 나는이 언어의 기초를 이해하기 시작했지만이 겉으로는 단순한 개념에 좌절감을 느끼고 있다고 생각했다. 당신의 도움을 주셔서 감사합니다.모듈 간 객체 참조 전달

window.onload = function() { 
    myApp.init(); 
    console.log(myApp.ctx);  // logs undefined 
}; 

var myApp = (function() {  

    var canvas, 
     ctx, 
     init = function() { 
      canvas = document.getElementById("canvas"); 
      ctx = canvas.getContext('2d'); 
      console.log(ctx);  // logs valid context2d object 
     }; 

    return { 
     init : init, 
     ctx : ctx 
    }; 

}()); 

myApp.board = (function() { 

    var ctx = myApp.ctx; 

    return { 
     ctx : function() { console.log(ctx); } // logs undefined 
    }; 

}()); 

답변

0

당신은 ctx에 대한 init() 정의 할 호출해야합니다. 그러나 myapp에 원래 값인 ctx가 포함되어 있기 때문에 그 시점까지는 너무 늦었습니다.

정확히 var ctx = myApp.ctx;과 동일한 문제가 있습니다. board이 정의되면 ctx의 값을 얻습니다. myApp.ctx이 변경되면 변경되지 않습니다.


이 작동합니다 :

var myApp = new function() { 
    var canvas; 

    this.init = function() { 
     canvas = document.getElementById("canvas"); 
     this.ctx = canvas.getContext('2d'); 
     console.log(this.ctx);  // logs valid context2d object 
    }; 
}; 

myApp.board = new function() { 
    this.ctx = function() { console.log(myApp.ctx); } 
}; 

new 키워드를 사용하여 기능은 생성자가 (즉시 호출) - this는 객체가 생성되기 말합니다.

+0

감사합니다. 이것이 "모범 사례"로 간주됩니까? 나는 새로운 키워드에 대해별로 좋지 않은 것을 읽었다. – Zelazny7