简体   繁体   English

Javascript:如何从this.img.onload = SomeLoadFunction调用this.Something();

[英]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 这显然不起作用,因为this.DoSomeStuff不再是Thing.DoSomeStuff并成为img.DoSomeStuff

So I guess what I need to know is, how can I call the Thing.DoSomeStuff() function from the img.onLoad .... 所以我想我需要知道的是,如何从img.onLoad ...中调用Thing.DoSomeStuff()函数。

On ES5 you can use: 在ES5上,您可以使用:

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. ps您当前的代码不合法​​。 Among other things, the variables have the wrong scope (or aren't properties of this ) and your function declaration syntax is incorrect. 其中,变量的作用域错误(或不是this属性),并且函数声明语法不正确。

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 . 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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