You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript原型函数绑定事件后Index变为NaN的原因及解决方法

问题原因

当你把listener.storeKey作为回调传给addEventListener时,这个函数的this指向发生了改变——它不再指向listener实例,而是指向触发事件的DOM元素(通常是document)。因为document上没有Index属性,this.Index就是undefined,执行undefined++后就变成了NaN。

而直接调用listener.storeKey()时,函数的this是通过调用者(.前面的listener)绑定的,所以this指向listener实例,能正常修改Index值。

解决方法

有几种简单的方式可以修复:

方法1:用bind绑定this

bind方法会返回一个新函数,强制让函数内部的this指向指定对象:

addEventListener("keydown", listener.storeKey.bind(listener));

方法2:用箭头函数包裹回调

箭头函数的this会继承外层作用域的this,这里外层的this就是listener所在的作用域,所以能正确指向实例:

addEventListener("keydown", (keyEvent) => listener.storeKey(keyEvent));

方法3:在构造函数里提前绑定方法

如果不想每次绑定都写bind,可以在构造函数里提前把方法的this绑定好:

const Key = function(){
    this.Index = 0;
    // 提前绑定this到当前实例
    this.storeKey = this.storeKey.bind(this);
}

Key.prototype.storeKey = function(key){
    this.Index++;
    console.log(this.Index);
}

const listener = new Key();
addEventListener("keydown", listener.storeKey); // 现在可以正常工作

内容的提问来源于stack exchange,提问作者WhyNot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 00:53:13