【问题标题】:Cannot extend a class, extra methods undefined无法扩展类,未定义额外方法
【发布时间】:2019-01-21 14:02:55
【问题描述】:

假设我有以下课程:

import EventEmitter from 'event-emitter';

export default class SharedChannel extends EventEmitter {
  constructor(opts) {
    super();
    console.log('SharedChannel constructor');
  }

  send(event, data) {
    console.log('SharedChannel send');
  }
}

在我的应用程序中,我尝试使用该类:

import SharedChannel from './lib/SharedChannel';
const channel = new SharedChannel();
channel.send('sessionData', 'Some session data goes here');

我收到以下错误:

未捕获的类型错误:channel.send 不是函数

EventEmitter 类中的方法确实有效,但我的 send 方法无效。例如,我可以致电channel.emit()。此外,我可以从该类构造函数中访问类方法。例如,我可以在super() 之后立即调用channel.send()。我可以通过在构造函数中调用this.send = function() { ... 来绕过它,但当然,这不是必需的。

这个应用程序是用 Webpack 和 Babel 构建的。在我的webpack.config.js 中,我有以下 Babel 规则:

{
  test: /\.js$/,
  exclude: /(node_modules|bower_components)/,
  use: {
    loader: 'babel-loader',
    options: {
      presets: ['@babel/preset-env']
    }
  }
}

.babelrc:

{
  "presets": ["@babel/preset-env"]
}

包的版本:

"@babel/core": "^7.0.0-rc.1",
"@babel/plugin-proposal-object-rest-spread": "^7.0.0-rc.1",
"@babel/preset-env": "^7.0.0-rc.1",
"babel-loader": "^8.0.0-beta",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0"

关于如何解决这个问题的任何建议?

【问题讨论】:

    标签: javascript webpack ecmascript-6 babeljs es6-class


    【解决方案1】:

    您在滥用EventEmitter 的API。它不打算用作父类,它是一个mixin。如果我们以the usage documentation 为例:

    var ee = require('event-emitter');
    
    var MyClass = function () { /* .. */ };
    ee(MyClass.prototype);
    

    使用MyClass.prototype 调用ee 函数会将事件发射器逻辑混合到类原型中。同样,在您的示例中,您想要

    import EventEmitter from 'event-emitter';
    
    export default class SharedChannel {
      constructor(opts) {
        console.log('SharedChannel constructor');
      }
    
      send(event, data) {
        console.log('SharedChannel send');
      }
    }
    EventEmitter(SharedChannel.prototype);
    

    【讨论】:

      猜你喜欢
      • 2016-05-13
      • 2012-02-04
      • 2014-10-12
      • 1970-01-01
      • 2016-11-17
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多