Javascript:在父级中看不到定义为箭头函数的替代方法 [英] Javascript: overriden methods defined as arrow functions are not seen in parent

查看:318
本文介绍了Javascript:在父级中看不到定义为箭头函数的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用一个父类来为其子级提供一些基本功能.看起来大致像这样:

I am using a parent class in my app to provide some basic functionality to its children. It looks roughly like this:

class Base {
  constructor(stream) {
    stream.subscribe(this.onData)
  }

  onData(data) {
    throw new Error('"onData" method must be implemented')
  }
}

class Child extends Base {
  onData(data) {
    // do stuff...
  }
}

这很好用,当我实例化Child时,BaseChild.onData传递给stream 唯一的问题是范围.在Child.onData中,我大量使用了通过this关键字在child中定义的其他方法.因此,当我将此函数作为对stream的回调传递时,一切都会中断.明显的解决方案是这样的:

That works fine and when I instantiate the Child, Base passes Child.onData to the stream The only problem is scope. In Child.onData I make a heavy use of other methods defined in child via this keyword. So when I pass this function as a callback to the stream, everything breaks. The evident solution is this:

class Base {
 constructor(stream) {
   stream.subscribe(this.onData)
 }

 onData = (data) => {
   throw new Error('"onData" method must be implemented')
 }
}

class Child extends Base {
 onData = (data) => {
   // do stuff...
 }
}

这确实解决了范围问题,但是现在传递给stream的函数始终是Base.onData,这会引发错误.通常,我可以做类似将Child.onData传递给Base构造函数的操作.那会行得通,但是我想找到的是一个更优雅的解决方案(如果存在的话)

That does solve problems with scope, but now the function that is being passed to the stream is always Base.onData which throws errors. Generally, I could do something like passing the Child.onData to Base constructor. That would work, but what I would like to find is a more elegant solution to this, if it exists

推荐答案

这就是为什么

That's why arrow functions in class properties are not that great. If you translate it to a normal ES6 class, this is what happens:

class Child extends Base {
  constructor(...args) {
    super(...args);
    this.onData = (data) => {
      // do stuff...
    };
  }
}

现在很明显为什么不能在Base构造函数中使用该属性.

It's rather evident now why using the property inside the Base constructor doesn't work.

相反,您应该使用常规方法定义并通过将方法绑定到父构造函数中来处理上下文问题:/p>

Instead, you should use normal method definitions and handle the context problem by binding the method inside the parent constructor:

class Base {
  constructor(stream) {
    if (this.onData == Base.prototype.onData)
      throw new Error('"onData" method must be overridden')
    this.onData = this.onData.bind(this);
    stream.subscribe(this.onData)
  }

  onData(data) {}
}

class Child extends Base {
  onData(data) {
    // do stuff...
  }
}

这篇关于Javascript:在父级中看不到定义为箭头函数的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆