2013-04-04 71 views
0

我正在使用自調用匿名函數來同時創建對象和實例。最後創建的對象覆蓋第一個對象的屬性。這是爲什麼?自我調用匿名函數互相覆蓋

<script> 
    LF = '<br/>'; //line feed 

    // object a with property name 
    !function() { 
     window.a = this; // make global object 

     this.name = 'a'; 

     document.write('inside: a.name=' + this.name + LF); 
    }(); 


    // object b with property name 
    !function() { 
     window.b = this; // make global object 

     this.name = 'b'; 

     document.write('inside: b.name=' + this.name + LF); 
    }(); 


    document.write('outisde: ' + ' a.name=' + a.name + ' b.name=' + b.name + LF); 

</script> 

結果:

inside: a.name=a 
inside: b.name=b 
outisde: a.name=b b.name=b 
+1

除了答案。你可以通過這種方式改變你的代碼來實現它:'new function(){window.a = this; ...}' – 2013-04-04 14:45:22

回答

3

在你的兩個函數中,thiswindow。所以this.name參考相同變量inisde 職能。