0

I was wondering whether I could get the parent object of a method - something like this:

ImageAsset = function (path) {
    this.ready = false; // I want the image.onload function to change this variable.

    this.image = new Image;
    this.image.onload = function () {
        thisParent.ready = true;
    };

    this.path = path;

    this.image.src = this.path;
};

Is there any way that I could do this? Thanks!

Bentley Carr
  • 672
  • 1
  • 8
  • 24

3 Answers3

1

You can if you use a variable

ImageAsset = function (path) {

    var that = this; // store the value of "this"

    this.ready = false;

    this.image = new Image;

    this.image.onload = function () {
        that.ready = true;
    };

    this.path = path;

    this.image.src = this.path;
};
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

I'd say:

ImageAsset = function (path) {
    this.ready = false; // I want the image.onload function to change this variable.

    this.image = new Image;
    var parent = this;
    this.image.onload = function () {
        parent.ready = true;
    };

    this.path = path;

    this.image.src = this.path;
};
jcaron
  • 17,302
  • 6
  • 32
  • 46
0

There are generally two ways to do this.

You can bind the executing scope of your function to "parent".

this.image.onload = function () {
        this.parent.ready = true;
 }.bind(this);

Note, bind is only available for certain browsers. So you'll proabaly want to use a polyfill so you can use bind in all browsers. Also, many Javascript frameworks provide equivalents of the bind function. For example, jQuery provides proxy.

this.image.onload = $.proxy(function () {
    this.parent.ready;
}, this);

Make a "parent" closed over variable.

var parent = this;
this.image.onload = function () {
    parent.ready = true;
};

Personally, I tend to go with option 1.

Community
  • 1
  • 1
Steven Wexler
  • 16,589
  • 8
  • 53
  • 80