I’m making a class that loads an image and calls its method after loading.
function Texture(){
this.afterload = function(){
document.write("loaded!");
}
this.load = function(name){
this.img = new Image();
this.img.src = name;
this.img.onload = function(){
// there is the problem - how to pass "this" to anonymous function?
this.afterload();
}
}
}
texture = new Texture();
texture.load("something.png");
// now it should write "loaded" after loading the image.
but the problem is passing a link to the object. When I use this, it doesn’t work.
So is there a way to pass object instance to an anonymous method?
You just need to copy
thisto a lexical variable:The anonymous function will “capture” or “close over” that variable, and will still be able to refer to it even after its containing function has returned.