0

我有这样的课

var grid = function () {

    this.cell = null;

    this.loadImage = function () {

       var image = new Image();
       var object = this;

       image.src = "blah";

       $(image).load(function () { 
           object.cell = this;                    
       });
    }

    this.showImage = function () {
       alert(object.cell); // This should print [object Object] ... but it print null;
    }
}

在从 loadImage 函数加载调用的图像之后调用 showImage 函数。有谁知道为什么 object.cell 为空...我在 loadImage 中引用了这个对象。

4

2 回答 2

3

object中未定义showImage

于 2012-02-06T22:15:53.013 回答
0

这是我认为你应该做的:

var grid = function () {

    this.cell = null;

    this.loadImage = function () {

        var image = new Image();

        image.addEventListener("load", (function (obj) { 
            return function () {
                obj.cell = this;                    
            };
        })(this));

        image.src = "http://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg";

    }

    this.showImage = function () {
        alert(this.cell);
    }
}
于 2012-02-06T22:19:16.150 回答