Tag: 扩展了

单例inheritanceBuggy行为

我已经发现在使用Singleton模式的JavaScript es6inheritance中的马车行为。 代码是 : let instanceOne = null; class One { constructor() { if (instanceOne) return instanceOne; this.name = 'one'; instanceOne = this; return instanceOne; } method() { console.log('Method in one'); } } let instanceTwo = null; class Two extends One { constructor() { super(); if (instanceTwo) return instanceTwo; this.name = 'two'; instanceTwo = this; […]

在扩展EventEmitter的ES6类定义中设置事件侦听器

我想要一些预定义的自定义侦听器,这些自定义侦听器已经定义了这个类的定义 (就像'newListner'事件中的构build一样)。 所以我不想在构造函数中绑定它们,因为它将在该类的每个新实例上执行。 这个怎么做? 修改原型? 有没有可能? 我到目前为止: class Cat extends EventEmitter { // just added for demonstration, I don't want this! constructor() { super(); // does fire this.on('wave', function() { console.log('constructor wave'); }); } } // compiles but does not fire Cat.prototype.on('wave', function() { console.log('prototype wave'); }); var cat = new Cat(); cat.emit('wave');