javascript - 传递“this”抛出函数
问题描述
我试图在每次更新时存储输入的值(在数组中)。我有多个输入结构:
<input class="inf" key="213" type="CUSTOM" value="val">
然后我有这个工作功能:
$('.inf').on('keyup', function () {
clearTimeout(temp2);
temp2= setTimeout(updateValues.call(this), doneTypingInterval);
});
但是 setTimeout 不起作用,所以我使用了这个解决方案并将其更改为:
temp2= setTimeout(function () {updateValues.call(this);}, doneTypingInterval);
现在,setTimeout
正在工作,但是当updateValues
达到时,所有 3 个变量都是“未定义的”。
更新值函数:
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);
};
问题是 in 中的this
对象updateValues
是我通过call
. 有什么建议么?
解决方案
您的问题的直接答案是使用.bind()
而不是.call()
:
temp2 = setTimeout(updateValues.bind(this), doneTypingInterval);
或使用箭头功能:
temp2 = setTimeout(() => { updateValues.call(this); }, doneTypingInterval);
更多关于如何this
在这个很棒的答案中找到作品
推荐阅读
- android - Hyperledger Iroha Android - CommandService Stateless 无效 tx - 格式错误的 creator_account_id,传递值:'' -
- java - 了解构造函数的有界泛型参数
- java - 如果 readCount 为零,如何跳过 itemWriter
- hadoop - HRegionServer 启动错误
- google-chrome - 在 Chrome 中,我可以阻止 Google 搜索结果中的视频和图像吗?
- pandas - 将熊猫数据框转换为 snap.py
- css - 什么时候“首选最小宽度”大于 CSS 中的“可用宽度”?
- django - 带有 PostgreSQL 错误消息的 Django:django.db.utils.ProgrammingError:运算符不存在:bigint = boolean
- python - 如何提取一个单词及其所有依赖项
- php - 使用 PHP 在 CURL 的标头中发布参数和数组