首页 > 解决方案 > 传递“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. 有什么建议么?

标签: javascriptjqueryajax

解决方案


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

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

或使用箭头功能:

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

更多关于如何this这个很棒的答案中找到作品


推荐阅读