问题描述
我试图在每次更新时将输入的值存储在一个数组中。 我有以下结构的多个输入:
<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