在 javascript 中将“this”引用传递给方法的提示

Tips on passing "this" reference to a method in javascript

本文关键字:方法 提示 引用 中将 javascript this      更新时间:2023-09-26

所以对于下面的代码,我试图将外部函数的"this"关键字传递到draw_bldText(...)函数中。但是我该怎么做呢?当我在执行中调用它时,"this"指的是函数作用域内。我想要来自this.piece的"this"关键字。

我希望我的问题有意义,我是javascript的新手

this.myDrawFunction;
this.piece = this;
switch(image) {
    case "blank":
        break;
    case "bldText":
    myDrawFunction = {
        execute : function() {
            draw_bldText(this, this_popup.context, this_popup.focus);       
        }
        };
    . . .
    . . .
    default:
        break;
}

你需要将一个局部变量绑定到 this ,并使用它,以便它保存在闭包中:

some_func() {
    var that = this;
    myDrawFunction = {
        execute: function() {
            draw_bldText(that, this_popup.context, this_popup.focus);
        }
    };
}