为什么事件侦听器中的“ this”是窗口而不是元素?

时间:2018-12-11 06:08:27

标签: javascript this

<tr v-for="(row, powerIndex) in powers">
    <td :class="powerlabelclass(row)">{{ row.name }}</td>
    <td class="power-item" v-for="turn in turns">
        <div v-if="row.expression">
            <input :class="poweritemclass(row)" type="number" :tabindex="tabindex(powerIndex, turn)" v-model="calculatepower(powerIndex, turn)" />       
        </div>
        <div v-else>
            <input :class="poweritemclass(row)" type="number" :tabindex="tabindex(powerIndex, turn)" v-model="row.turns[turn]" />        
        </div>
    </td>
</tr>

这不符合我的预期,因为我在输入上调用了事件监听器。我认为“ this”将作为输入,但它是指窗口。我对这是为什么感到困惑。如果有人可以解释,那就太好了。

为解决这个问题,我创建了一个函数并将其传递给侦听器。

const input= document.querySelector('.search');

input.addEventListener('keyup', e=>{
  console.log(this.value);
});

我仍然对为什么使用这种方式允许'this'引用输入感到困惑。

2 个答案:

答案 0 :(得分:3)

箭头功能(() => {})没有像this那样的专用上下文,但是可以从其定义的任何范围继承。

如果您想获得正确的this,则需要像以前一样定义“正常”功能。

答案 1 :(得分:2)

您无法在箭头功能中重新绑定this。使用箭头功能时,this由词法作用域确定(定义了功能)。您应该在此处使用常规函数:

const input= document.querySelector('.search');
 

// use a regular function and this will be what you expect
input.addEventListener('keyup', function(e){
  console.log(this.value);
});
<input class="search" />