简体   繁体   中英

JavaScript - Can I get the parent object of a method?

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!

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM