Endless
Endless

Reputation: 37806

Add class properties to regular function

Normally I would create a class and extend it with es6 classes

But this time i got just a regular function that i would like to add the EventEmitter to

function hello(){
  return 'world';
}

hello(); // world

The function is not a constructor and should not be called with new. Now i would also like to have the EventEmitter properties added to this function (much like jquery's $ where it's both a function and a object)

How would i achieve this?

I was thinking something in terms of:

const {EventEmitter} = require('events')

function hello(){
  hello.emit('something', 'called foo')
  return 'world'
}

const myEE = new EventEmitter()
Object.assign(hello, myEE)

hello.on('something', console.log) // called foo
hello() // world

but this doesn't work. Do you have any suggestion? hope there is a better way then doing something like hello.on = myEE.on for all of the event's properties

Upvotes: 0

Views: 38

Answers (1)

Sergey Lapin
Sergey Lapin

Reputation: 2693

Your example doesn't work because all the methods you are looking for (e.g. on) exist not in the object itself, but rather in its prototype chain.

To make it work, you can

Object.setPrototypeOf(hello, myEE)

instead of

Object.assign(hello, myEE)

Upvotes: 1

Related Questions