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

0 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('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>
Run Code Online (Sandbox Code Playgroud)

结果:

inside: a.name=a 
inside: b.name=b 
outisde: a.name=b b.name=b
Run Code Online (Sandbox Code Playgroud)

mic*_*nic 8

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