简体   繁体   English

Javascript覆盖类方法

[英]Javascript override class method

I'm trying to use a class from a library but want to override one of its methods.我正在尝试使用库中的一个类,但想覆盖它的一个方法。 This is how the class is defined:类是这样定义的:

class A {
  constructor (options) {
    this._searchForm = options.searchForm 
    this._searchForm.addEventListener('submit', this.submitHandler.bind(this))
  }

  submitHandler = (e) => {
    console.log('Default')
  }
}

I want to override the submitHandler function and so this is what i did:我想覆盖submitHandler函数,所以这就是我所做的:

class B extends A {
  submitHandler = (e) => {
    console.log('New')
  }
}

However, it's still calling the old function.但是,它仍在调用旧函数。 What am i doing wrong?我究竟做错了什么?

A class constructor must not call (or, in this case, bind) on overridable method (see also here ).类构造函数不得调用(或在本例中为绑定)可覆盖的方法(另请参见此处)。 It probably shouldn't even install event listeners - that's not the job of a constructor.它甚至可能不应该安装事件侦听器——这不是构造函数的工作。 But if you still want to do it, don't use class fields but method declarations:但是,如果您仍然想这样做,请不要使用类字段,而是使用方法声明:

class A {
  constructor (options) {
    this._searchForm = options.searchForm 
    this._searchForm.addEventListener('submit', this.submitHandler.bind(this))
  }

  submitHandler(e) {
    console.log('Default')
  }
}
class B extends A {
  submitHandler(e) {
    console.log('New')
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM