2011-11-06 3 views
1

안녕하세요 저는이 모듈 패턴 변형을 사용하고 있으며 부모 객체에 액세스하는 가장 좋은 방법을 찾고 있습니다. 부모 개체가 무엇인지 알 수있는 방법이 없다는 것을 알고 있으므로 생성자에 컨텍스트를 포함하고 싶습니다. 이게 효과가있을 거라 생각했는데 어떤 생각이 들지?javascript 모듈 패턴 변형을 사용하는 동안 부모 객체에 액세스

$(document).ready(function(){ 

    var main = new Main(); 

}); 


function Main() { 

    var one = 'hello'; 

    init(); 

    function init() { 
     var data = new Data(this); 
     var two = data.load(); 
     console.log(one+' '+two); 
     data.output(); 
    } 

} 

function Data(context) { 

    // public vars/methods 

    var pub = { 
     'load' : function() { 
      return ('world'); 
     }, 
     'output' : function() { 
      var one = context.one // <-- what should this be? 
      var two = this.load(); 
      console.log (one+' '+two); 
     } 
    } 

    return pub; 

} 

출력은 다음과 같습니다 당신이 new 연산자와 생성자 함수를 호출 할 때, 당신은 기본적으로

function Main(){ 
    var this = //magic new object 
       //provided by the runtime 

    //your code comes here 

    return this; 
    //because your Data function returns a value, 
    // you never get to this line. Perhaps you should use 
    // a regular non-constructor data() function instead? 
} 

같은 일을하고있다

hello world 
undefined world 

답변

2

당신은 var있는 전용 변수를 선언 할 때 그것은 단순한 변수 일 뿐이며 다른 것은 없습니다. 당신이 일을 추가 할 경우 this 그렇게 명시 적으로

this.one = 'hello'; 

을해야하지만 그게 전부는 아닙니다! this이 아니며 어휘 범위이므로 init 함수가 외부에서 this과 관련이없는 다른 this을 가져옵니다 (이 경우 undefined이 나옵니다). 당신이 내부 함수에 this를 사용할 때처럼, 해결 방법을 수행해야합니다


var that = this; 

function init(){ 
    new Data(that); 
} 
init(); 
는 말했다, 당신의 모범이 모두를 할 필요가 왜 표시되지 않습니다 . 나는 constructor 함수 (그리고 new)를 사용하는 것을 선호한다. (prototypal 상속을 사용하고 싶을 때). 귀하의 경우 아마도 "덜 OO"접근 방식으로 벗어날 수 있습니까?

//main doesn't need to be a class 
// this is not Java :) 
function main(){ 

    //just a plain object for the 
    //context. Create a separate class 
    //if you really need to... 
    var context = { 
     one: 'hello' 
    }; 

    var data = new Data(context); 
    var two = data.load(); 
    console.log(one+' '+two); 
    data.output(); 
} 
+0

대답 해 주셔서 감사합니다. 필자의 예제에는 복잡성이 더해질 필요가 없다는 것에 동의하며 패턴을 보여주기 위해 가능한 한 간단하게 만들었습니다. 다시 한 번 감사드립니다! – pixelscript

관련 문제