But in your snippet, you wanted to have dog.bark(), in that case see below
class Dog {
addEventListener(method,callback) {
this[method] = callback;
}
removeEventListener (method) {
delete this[method];
}
}
The above will work as
const dog = new Dog();
dog.addEventListener('bark', ()=>console.log("bow"));
dog.bark() // logs => bow
dog.addEventListener('somethingsomething', ()=>{ /*do something*/ })
dog.removeListener('bark');
We can implement tiny class as EventEmitter pattern
class Dog {
constructor() {
this.listeners = {};
}
emit(method, payload = null) {
const callback = this.listeners[method];
if(typeof callback === 'function'){
callback(payload);
}
}
addEventListener(method,callback) {
this.listeners[method] = callback;
}
removeEventListener (method) {
delete this.listeners[method];
}
}
And we can use this class like this
const dog = new Dog();
dog.addEventListener('bark',(customSound)=>console.log(customSound || "Bow Bow"));
dog.addEventListener('eat', ()=>console.log("eating yum yum") );
dog.emit('bark') // logs => Bow Bow
dog.emit('bark', 'i can talk humans') // logs => i can talk humans
dog.emit('eat');
dog.removeEventListener('bark');
Note: it's raw implementation, not production ready code. Thanks.