0

我有一个带有诸如 this.pic_w、this.pic_h 等方法的 Pic 类。在该类的一个方法中,我初始化了一个 Image 对象并重写了它的一个方法。如何从 Pic 的方法之一内部但不从 Pic 继承的 Image 重新定义方法访问我的 Pic 变量(this.pic_w、this.pic_h)?以下是类变量:

Pic.prototype = new DaVinci();
Pic.prototype.constructor = Pic;
function Pic(canvas) {
    this.canvas = canvas;
    this.pic = "";
    this.resize_w = 200;
    this.resize_h = 200;
    this.pic_w;
    this.pic_h;
}

...一些其他方法...

Pic.prototype.draw = function( img_src, pos_x, pos_y ) {
    this.setPos(pos_x,pos_y);
    this.setPic(img_src);
    var ctx = this.setWidget();
    var x = this.pos_x;
    var y = this.pos_y;
    var img = new Image();
    img.src = this.pic;
    img.onload = function() {
        // How can I access Pic class methods and variables from here?
            ctx.drawImage(img, x, y, this.width, this.height);
    }
}
4

1 回答 1

1

通常这是通过在同一个闭包中保存对对象的引用来完成的。就像是:

Pic.prototype.draw = function( img_src, pos_x, pos_y ) {
    var that = this; //Remember "this" so you can use it later

    this.setPos(pos_x,pos_y);
    this.setPic(img_src);
    var ctx = this.setWidget();
    var x = this.pos_x;
    var y = this.pos_y;
    var img = new Image();
    img.src = this.pic;
    img.onload = function() {
        // Here I can access this.width, this.height values.
        // I want to save those values as Pic.pic_w, and Pic.pic_h
        ctx.drawImage(img, x, y, this.width, this.height);
        that.pic_w = this.width; //Now you can set the properties of "that"
        that.pic_h = this.height;
    }
    return ss;
    // END
}
于 2012-08-16T22:11:44.950 回答