javascript - 无法扩展类,未定义额外方法
问题描述
假设我有以下课程:
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"
关于如何解决这个问题的任何建议?
解决方案
您正在滥用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);
推荐阅读
- android - Xamarin Forms Maps MoveToLastRegionOnLayoutChange 未按预期工作
- c# - 有效地找到两个序列中的第一个公共元素
- reactjs - 显示来自 Mongodb (MERN) 的图像
- c - 如何让我的 C 代码读取并显示 C 文件中的多行?
- php - 使用PHP将数据从csv导入pdf表格
- flutter - Flutter:如何定位当前可访问的 Scaffold
- regex - 返回 C++ 中正则表达式的所有可能匹配项
- infinispan - ConnectTimeoutException infinispan
- javascript - 如何在javascript中将数组拆分为给定的数字
- php - 使用 PHP API 将文件上传到 Google Drive