1

Here's what I have so far: http://jsfiddle.net/nxCFn/

var il = new ImageLoader();

function ImageLoader() {
    this.n = 2;

    this.load = function() {
        //obviously, the this = the image and not the original instance of ImageLoader :(
        this.n++;
        console.log(this.n);
    }

    this.imgnam = "http://www.google.com/images/errors/logo_sm.gif";

    this.img = new Image();
    this.img.src = this.imgnam;
    this.img.onload = this.load;
}​

Because the image is calling .load() this from load points to the image. I want to make this from load point to the ImageLoader instance it "belongs" to.

jeremy
  • 9,965
  • 4
  • 39
  • 59
adrianton3
  • 2,258
  • 3
  • 20
  • 33

3 Answers3

1

Copy the this reference to a local variable, and make the event handler an anonymous function so that the local variable is caught in the closure for the function:

var that = this;

this.img.onload = function() { that.load() };
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1
var that = this;
this.img.onload = function () { that.load();}
Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
1

Use Function.prototype.bind

this.img.onload = this.load.bind(this);

Or you can use it right here since you make a new function for each instance.

this.load = function() {
    this.n++;
    console.log(this.n);
}.bind(this);


this.img.onload = this.load;

To support old browsers, you can make your own binder function instead.

function _binder(func, ctx /*, arg1, argn */) {
    var _slice = Array.prototype.slice,
        bound_args = _slice.call(arguments, 2);
    return function() {
        return func.apply(ctx, bound_args.concat(_slice.call(arguments)));
    }
}

Then do this.

this.img.onload = _binder(this.load, this);
gray state is coming
  • 2,107
  • 11
  • 20