在循环中引用这个

Referring to this in a loop?

本文关键字:引用 循环      更新时间:2023-09-26
p._initEvents = function() {
    $(window).on('drop', this.onDrop.bind(this)).on('dragover', this.onDragOver);
};

p.onDrop = function(e) {
    e.preventDefault();
    var files = e.originalEvent.dataTransfer.files;
    $.each(files, function(index, file){
        this.showTemplate();
    });
};
p.showTemplate = function() {
    console.log('show template');
};

我试图运行this. showtemplate(),但错误说它是未定义的,我相信这与绑定这个有关。

我已经为onDrop方法绑定了这个,但我不确定在循环中访问这个的最佳方法是什么?

你可以做的一件事是在$.each()函数之外声明一个this变量…

p.onDrop = function(e) {
    e.preventDefault();
    var myThis = this;
    var files = e.originalEvent.dataTransfer.files;
    $.each(files, function(index, file){
        myThis.showTemplate();
    });
};