How to declare a javascript function with properties in one line/command?

Viewed 78

For now, I can do:

const f = () => 'result';
f.customProperty = 5;

Is it possible to do this in one command? Something like:

const f = {
  () => 'result',
  customProperty: 5,
};

Ok, there is a possibility:

f = (() => {
  const f = () => 'result';
  f.customProperty = 5;
  return f;
})();

But... Isn't there something more elegant?

1 Answers

With Object.assign, you can pass the function expression as the first argument, then pass an object with the customProperty property as the second argument:

const f = Object.assign(() => 'result', {customProperty: 5});

console.log(f.customProperty);
console.log(f());

Related