javascript - 如何将对象的链接传输给匿名函数?

标签 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(){
            // 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复制到词法变量:

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

匿名函数将“捕获”或“关闭”该变量,并且即使在其包含函数返回后仍然可以引用它。

关于javascript - 如何将对象的链接传输给匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9319041/

相关文章:

javascript - 当通过钩子(Hook)传递时,setState 函数是否应该是 useEffect 的依赖项

javascript - 如何测试一个 float 是否为整数 "within machine precision"?

javascript - 未知函数语法导致 JSHint 警告

c# - 匿名函数转换

javascript - 从 Controller 观察服务的变化

ruby - 为什么我不能在模块中扩展 Fixnum 类并使用它?

java - 在 Java 方法中传递和使用 Class

java - 我应该将测试方法放在单独的类中吗?如果是这样,怎么办?

c++ - 匿名函数 C++

javascript - 正则表达式删除所有不跟在数字后面的句点