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
4

2 回答 2

8

因为在你的情况下window === thisand 。在这里阅读更多:http: //unschooled.org/2012/03/understanding-javascript-this/window === awindow === b

于 2013-04-04T14:33:38.587 回答
3

在您的两个函数中,thiswindow. 所以在两个函数中this.name引用相同的变量。

于 2013-04-04T14:34:08.690 回答