我正在使用自調用匿名函數來同時創建對象和實例。最後創建的對象覆蓋第一個對象的屬性。這是爲什麼?自我調用匿名函數互相覆蓋
<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
除了答案。你可以通過這種方式改變你的代碼來實現它:'new function(){window.a = this; ...}' – 2013-04-04 14:45:22