简体   繁体   中英

Javascript: How to call this.Something() from this.img.onload = SomeLoadFunction;

Ok I have some code similar to this...

Thing function () {    
  var img = new Image;    
  DoSomeStuff function() {    
  //Some stuff here that can't be done until my img is loaded...    
};

InitMe function(src) {    
  this.img.onLoad = this.DoSomeStuff;     
  this.img.src = src;    
};    
}

var Test = new Thing();    
Test.InitMe("some string");

Which obviously doesn't work because this.DoSomeStuff stops being Thing.DoSomeStuff and becomes img.DoSomeStuff

So I guess what I need to know is, how can I call the Thing.DoSomeStuff() function from the img.onLoad ....

On ES5 you can use:

this.img.onLoad = this.DoSomeStuff.bind(this);

or:

var self = this;
this.img.onLoad = function() {
    self.DoSomeStuff();
}

ps your current code isn't remotely legal. Among other things, the variables have the wrong scope (or aren't properties of this ) and your function declaration syntax is incorrect.

You may want this

function Thing() {    
    this.img = new Image;    
    this.DoSomeStuff=function(){
        // do something
    };

    var self=this;
    this.InitMe=function(src) {   
        self.img.src = src;
        self.img.onload = function(){
            self.DoSomeStuff();
        }
    };    
}

var Test = new Thing();    
Test.InitMe("example.png");​

DEMO .

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