javascript onload如何在实例中工作?

时间:2016-01-02 23:08:07

标签: javascript

这是我试图做的简单版本:

<script type="text/javascript">
    function Example(position) {
        this.position = position;
        instance = this;

        img = new Image();
        img.src = 'http://www.gazette-ariegeoise.fr/IMG/jpg/test.jpg';

        console.log(this.position);
        //logs as expected 1 than 2 on the second


        img.onload = function() {
            console.log(instance.position); 
            //logs 2 twice
        }
    }

    ex1 = new Example(1);
    ex2 = new Example(2);
</script>

以某种方式onload函数记录实例2的位置两次,

为什么?

1 个答案:

答案 0 :(得分:4)

instance是全局的,因此第二次调用Example()会覆盖第一个。

使用var创建局部变量。

更好的是,use "use strict";因此它不会让你创造偶然的全局变量。