Javascript对象方法无法访问/未定义

时间:2016-06-24 10:42:26

标签: javascript object undefined

首先,我知道有数百万这样的问题。但我无法帮助我。

我在加载所有图像后调用draw方法。如您所见,当我尝试在draw方法中访问变量(loadedImages, this)时,我得到了未定义。

为什么会发生这种情况?我怎样才能获得这些变量?

var canvas = $('#area')[0],
    context = canvas.getContext('2d');

function Character() {
    return {
        images: ["hair.png", "head.png", "mouth.png"],
        loadedImages: {},
        init: function() {
            this.loadImages();
        },
        loadImages: function() {
            var loaded = 0,
                imagesLength = this.images.length,
                draw = this.draw;

            for(var i = 0; i <= imagesLength - 1; i++) {
                var image = new Image(),
                    bodyPart = this.images[i];

                image.onload = function() {
                    loaded++;

                    if(loaded == imagesLength) {
                        draw();
                    }
                };

                image.src = 'characters/Canser/' + bodyPart;

                this.loadedImages[bodyPart.split(".")[0]] = image;
            }
        },
        draw: function() {
            console.log(this); // undefined???
        }
    };
}

var canser = new Character();

canser.init();

1 个答案:

答案 0 :(得分:2)

将其存储在其中并使用that.draw()

var canvas = $('#area')[0],         context = canvas.getContext('2d');

function Character() {
    return {
        images: ["hair.png", "head.png", "mouth.png"],
        loadedImages: {},
        init: function() {
            this.loadImages();
        },
        loadImages: function() {
            var loaded = 0,
                that = this,
                imagesLength = this.images.length,
                draw = this.draw;

            for(var i = 0; i <= imagesLength - 1; i++) {
                var image = new Image(),
                    bodyPart = this.images[i];

                image.onload = function() {
                    loaded++;

                    if(loaded == imagesLength) {
                        that.draw();
                    }
                };

                image.src = 'characters/Canser/' + bodyPart;

                this.loadedImages[bodyPart.split(".")[0]] = image;
            }
        },
        draw: function() {
            console.log(this); // undefined???
        }
    };
}