2011-11-06 78 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; 

} 

輸出是:

hello world 
undefined world 

回答

2

當你調用與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? 
} 

當你聲明與var一個私有變量它將只是一個簡單的變量,沒有別的。如果您想要的東西添加到您this需要做這樣明確地

this.one = 'hello'; 

但是,這還不是全部! this而不是詞彙範圍,所以init函數從外部獲取與this無關的其他this(這解釋了您獲得的undefined)。當你想在內部函數中使用this你需要做一個變通方法,像:

var that = this; 

function init(){ 
    new Data(that); 
} 
init(); 

也就是說,只要你的榜樣,我不明白爲什麼你需要做的這一切。只有在嚴格需要時(我想利用原型繼承)時,我才喜歡使用構造函數(和new)。在你的情況下,也許你可以用「少OO」的方法逃脫?

​​
+0

謝謝你的回答,這是非常清楚,只是我以後。我同意我的例子不需要增加複雜性,我只是儘可能簡單地展示模式。再次感謝! – pixelscript

相關問題