Javascript 如何将指向对象的链接传输到匿名函数?
我正在创建一个类,用于加载图像并在加载后调用其方法Javascript 如何将指向对象的链接传输到匿名函数?,javascript,class,anonymous-function,Javascript,Class,Anonymous Function,我正在创建一个类,用于加载图像并在加载后调用其方法 function Texture(){ this.afterload = function(){ document.write("loaded!"); } this.load = function(name){ this.img = new Image(); this.img.src = name; this.img.onload = function(){
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.
但问题是传递到对象的链接。当我用这个的时候,它不起作用
那么有没有一种方法可以将对象实例传递给匿名方法呢?您只需要将
这个
复制到一个词法变量:
this.load = function(name){
this.img = new Image();
this.img.src = name;
var _this = this;
this.img.onload = function(){
_this.afterload(); // use local variable, '_this', instead of 'this'
};
};
匿名函数将“捕获”或“关闭”该变量,并且即使在其包含函数返回后仍能引用该变量。定义另一个指向内部函数外部对象的变量,并使用该变量引用它
var that = this;
this.img.onload = function(){
that.afterload();
};
我想就是这样!非常感谢你。