Declare function with property in one statement?

Viewed 64

I know that I can create a function:

const fn = () => {}

And I know that I can attach a property to it:

fn.a = 'a'

Can I use some kind of object literal syntax to do what I did above in one statement?

I'm thinking something along the lines of:

const fn = {
  (): {},
  a: 'a'
}
2 Answers

You could do it in one statement like this.

const fn = Object.assign(() => {}, { a: 'a' });

How about we make a little utility function to accomplish that?

function createFunc(func, props) {
  Object.keys(props).forEach((key) => (func[key] = props[key]));
  return func;
}

const f = createFunc(() => console.log("hello"), { a: "A", b: "B" });

f();
console.log(f.a);
console.log(f.b);

Related