Javascript 不知何故,我的班级没有';我无法定义一些变量

Javascript 不知何故,我的班级没有';我无法定义一些变量,javascript,oop,canvas,Javascript,Oop,Canvas,所以,我正在使用任何面向对象的选项来尝试创建一个整洁的静态图像类,所以我所要做的就是将所述类添加到画布中,它将自己绘制出来!为了测试是否一切正常,我添加了一些警报。现在,我的函数在第三次警报时开始发出“未定义” function StaticImage(imgsource, cancontext, ex, wy) { this.x = ex; this.y = wy; this.context = cancontext; alert("Image class in

所以,我正在使用任何面向对象的选项来尝试创建一个整洁的静态图像类,所以我所要做的就是将所述类添加到画布中,它将自己绘制出来!为了测试是否一切正常,我添加了一些警报。现在,我的函数在第三次警报时开始发出“未定义”

function StaticImage(imgsource, cancontext, ex, wy) {
    this.x = ex;
    this.y = wy;
    this.context = cancontext;
    alert("Image class instantiated! " + imgsource);
    this.draw = function () {
        this.image = new Image();
        this.image.src = imgsource;
        alert("Draw function called!");
        this.image.onload = function () {
            alert(this.image + " loaded! drawing on: " + this.context + " at: " + this.x + ":" + this.py);
        };
        this.cancontext.drawImage(this.image, this.x, this.y);
    }
}
因此,这就是类,这是HTML页面上使用的Javascript代码,用于保存画布。首先,它创建了图像bla.jpg,然后它做了同样的事情,只对类

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var bla = new Image();
bla.src = "bla.jpg";
bla.onload = function () {
    context.drawImage(bla, 50, 50);
};
var lol = new StaticImage("bla.jpg", context, 200, 200);
lol.draw();

我想这里的问题在于

  this.image.onload = function() {
    alert(this.image + " loaded! drawing on: " + this.context + " at: " + this.x + ":" + this.py);
  }
函数
onload
的作用域是存储在
this.image
中的对象。因此,函数中的
这个
表示图像本身。这个类的属性image、context、x和y可能没有定义

function StaticImage(src, context, x, y) {    
    this.x = x;
    this.y = y;
    this.context = context;

    // save reference to the instance
    var self = this; 

    // initialize the image at initialization 
    // time instead of at every draw
    self.image = new Image();
    self.image.onload = function() {
        // self will still refer to the current instance
        // whereas this would refer to self.image
        alert(self.image + " loaded! drawing on: " + self.context +
              " at: " + self.x + ":" + self.y);
    };
    self.image.src = src;

    alert("Image class instantiated! " + src);
}

// make draw function part of the prototype
// so as to have only 1 function in memory
StaticImage.prototype.draw = function() {
    alert("Draw function called!");
    this.context.drawImage(this.image, this.x, this.y);
};
​
注意:在设置onload处理程序之后设置image src也很重要,因为如果映像在缓存中,则可能会错过事件