传递“ this”抛出函数

问题描述

我试图在每次更新时将输入的值存储在一个数组中。 我有以下结构的多个输入:

<input class="inf" key="213" type="CUSTOM" value="val">

然后我有这个工作功能:

$('.inf').on('keyup',function () {
    clearTimeout(temp2);
    temp2= setTimeout(updateValues.call(this),doneTypingInterval);
});

但是setTimeout不起作用,所以我使用了this solution并将其更改为:

temp2= setTimeout(function () {updateValues.call(this);},doneTypingInterval);

现在,setTimeout在工作,但是当到达updateValues时,所有3个变量都是“未定义的”。

updateValues函数:

var updateValues= function(){
            
 key=$(this).attr("key");
 type=$(this).attr("type");
 value=this.value;
                
    upd={
        "name" : '"'+key+'"',"type" : '"'+type+'"',"value" : '"'+value+'"'
    };
 nw = nw.concat(upd);
 console.log(nw);
};

问题在于this中的updateValues对象是我与call一起传递的。有什么建议吗?

解决方法

您的问题的直接答案是使用.bind()而不是.call()

temp2 = setTimeout(updateValues.bind(this),doneTypingInterval);

或使用箭头功能:

temp2 = setTimeout(() => { updateValues.call(this); },doneTypingInterval);

有关this工作原理的更多信息,请参见this great answer

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...