4

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'
}
user1283776
  • 19,640
  • 49
  • 136
  • 276
  • 1
    I believe this article will help you out [Proper use of const for defining functions](https://stackoverflow.com/questions/33040703/proper-use-of-const-for-defining-functions) – slashroot Oct 08 '21 at 13:57
  • 1
    Take a look at : https://stackoverflow.com/a/20734003/16688813 – Tom Oct 08 '21 at 14:27
  • See also https://stackoverflow.com/q/31412639/1048572 – Bergi Oct 08 '21 at 14:58

2 Answers2

4

You could do it in one statement like this.

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

Wyck
  • 10,311
  • 6
  • 39
  • 60
1

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);
h-sifat
  • 1,455
  • 3
  • 19