能否将onchange函数作为JavaScript类的成员函数?
当然可以在类内部绑定onchange!你的实现只差一步
嗨,刚接触JavaScript遇到this相关的问题太正常啦,其实你完全可以把onchange绑定逻辑放到Product类内部,这样每个实例创建时就自动完成绑定,不用重复写代码。你之前的思路没问题,只是细节上有点小疏漏~
问题出在哪?
你注释里写的this.in.onchange = () => this.update();有两个小问题:
- 你定义的方法是
updatePrice,不是update,方法名写错了; - 这段代码没有放在类的
constructor里执行,所以不会被触发。
正确的实现方式
只需要把绑定逻辑放到constructor中,利用箭头函数保留this的指向(箭头函数会捕获当前类实例的this,而不是触发事件的input元素),这样每个产品实例创建时就会自动给对应的输入框绑定onchange事件:
class Product { constructor(name, price) { this.name = name; this.price = price; this.in = document.getElementById(this.name); // 直接在constructor里绑定onchange this.in.onchange = () => this.updatePrice(); } updatePrice() { this.price = this.in.value; console.log(`${this.name}的新价格:${this.price}`); } } // 现在实例化时不需要再手动绑定了! let myProductName1 = new Product('myProductName1', 200); let myProductName2 = new Product('myProductName2', 300);
为什么箭头函数能解决问题?
如果不用箭头函数,直接写this.in.onchange = this.updatePrice,那么当onchange触发时,this会指向触发事件的input元素,而不是Product实例,这时候this.price和this.in就不是你期望的类属性了。
箭头函数不会创建自己的this,它会继承外层作用域(也就是constructor执行时的Product实例)的this,所以能正确调用this.updatePrice并访问类的属性。
另一种绑定方式:使用bind
如果你不想用箭头函数,也可以用bind方法强制绑定this指向:
this.in.onchange = this.updatePrice.bind(this);
效果和箭头函数一样,只是写法稍显繁琐。
这样你就不用为每个实例单独绑定事件啦,代码复用性更高,完全符合你的需求~
内容的提问来源于stack exchange,提问作者fulvy
相关产品推荐
相关产品推荐

