Javascript 自调用匿名函数相互覆盖

Javascript 自调用匿名函数相互覆盖,javascript,javascript-objects,Javascript,Javascript Objects,我使用自调用匿名函数来同时创建对象和实例。最后创建的对象覆盖第一个对象的属性。为什么呢 <script> LF = '<br/>'; //line feed // object a with property name !function () { window.a = this; // make global object this.name = 'a'; document.write('in

我使用自调用匿名函数来同时创建对象和实例。最后创建的对象覆盖第一个对象的属性。为什么呢

<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>
因为在你的例子中,window==this和window==a和window==b。
阅读更多信息:

在两个函数中,这是一个窗口。因此,除了答案之外,this.name还引用了两个函数中的相同变量。

。您可以通过这种方式更改代码以使其正常工作:新函数{window.a=this;…}
inside: a.name=a 
inside: b.name=b 
outisde: a.name=b b.name=b