JuanCB
JuanCB

Reputation: 305

Reference class container in Javascript

I have a Pic class with methods such as this.pic_w, this.pic_h. Inside one of the methods of the class, im initializing an Image object and rewriting one of it's methods. How can I access my Pic variables (this.pic_w, this.pic_h) from the Image redefined method that is inside one of Pic's methods but does not inherit from Pic? Here are the class variables:

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;
}

...Some other methods...

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);
    }
}

Upvotes: 0

Views: 799

Answers (1)

Mike Christensen
Mike Christensen

Reputation: 91618

Usually this is done by saving a reference to the object within the same closure. Something like:

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
}

Upvotes: 1

Related Questions