javascript - 将 "this"引用传递给 javascript 中的方法的提示

标签 javascript function object reference this

因此,对于下面的代码,我尝试将外部函数的“this”关键字传递到draw_bldText(...)函数中。但我该怎么做呢?当我在执行中调用 this 时,“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;
}

最佳答案

您需要将局部变量绑定(bind)到 this,并使用它以便将其保存在闭包中:

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

关于javascript - 将 "this"引用传递给 javascript 中的方法的提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915676/

相关文章:

function - 当 Typescript 具有不同的参数计数时,有没有办法让 Typescript 认为函数类型不相等?

javascript - JS : How to automate going up "parentNode" as many times as needed

对象或静态中的 C++ 方法

java - 根据Java中对象属性的最常见值过滤对象的Arraylist

javascript - 这是什么怪物?

javascript - 如何让第二个 <script> 等待第一个 <script> 完成?

javascript - 如何使用 JavaScript 将 Byte[] 格式的图像转换为 Base64 字符串

javascript - 如何安装和使用 jQuery Chosen 插件?

ios - 当你在第一个 VC 中时,如何在第二个 VC 中运行一个函数?

javascript - 将对象的属性访问到嵌套数组中 - Javascript