首页 > 解决方案 > 无法扩展类,未定义额外方法

问题描述

假设我有以下课程:

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');

我收到以下错误:

未捕获的 TypeError:channel.send 不是函数

EventEmitter 类中的send方法确实有效,但我的方法无效。例如,我可以调用channel.emit(). 此外,我能够从该类构造函数中访问类方法。例如,我可以channel.send()super(). 我可以通过调用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"

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

标签: javascriptwebpackecmascript-6babeljses6-class

解决方案


您正在滥用EventEmitter. 它不打算用作父类,它是一个mixin。例如,如果我们查看使用文档

var ee = require('event-emitter');

var MyClass = function () { /* .. */ };
ee(MyClass.prototype);

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

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);

推荐阅读