JS使用class时点击按钮报错x is not a function问题求助
问题原因
报错的核心是事件回调的this指向发生了变化:你将this.butClick作为点击事件的回调传入时,回调触发时内部的this不再指向Test类的实例,而是指向触发点击的按钮DOM元素,DOM元素上不存在doThis方法,因此抛出函数未定义的错误。
可直接使用的解决方法
- 方案1:使用
bind绑定实例this
在绑定事件时通过bind方法强制将回调的this绑定为当前类实例,修改构造函数代码即可:
constructor() { this.button = document.getElementById("but1"); this.button.addEventListener("click", this.butClick.bind(this)); }
- 方案2:用箭头函数包裹回调
箭头函数会继承外层作用域的this(也就是类实例的this),不会被事件调用修改指向:
constructor() { this.button = document.getElementById("but1"); this.button.addEventListener("click", () => this.butClick()); }
- 方案3:将类方法定义为箭头函数
使用类字段语法直接把butClick定义为箭头函数,它的this会永久指向类实例:
class Test { constructor() { this.button = document.getElementById("but1"); this.button.addEventListener("click", this.butClick); } butClick = () => { console.log("clicked"); this.doThis(); } doThis(){ console.log("Inside doThis") } }
以上三种方案任选其一即可正常实现需求。
内容的提问来源于stack exchange,提问作者Vinurk
相关产品推荐
相关产品推荐

