0

Declaration in question:

let foo = { bar () {} };
{ bar: [Function: bar] }

This creates an object with a single property bar that is an arrow function and assigns it to foo.
So { bar: () => {} } is this { bar () {} }?
Can someone explain/expand on this?
Anyone have a reference to documentation on this?
Is there a term for this kind of declaration (that I can Google)?
Other than saving some keystrokes, any reason to use this kind of declaration?

nwayve
  • 2,291
  • 23
  • 33
  • 1
    It's one of the shortcuts that was added in ES6. – Barmar Aug 29 '23 at 16:24
  • Shorthand method definition: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#method_definitions `let foo = { bar () {} };` is short for `let foo = { bar: function () {} };`, not `let foo = { bar: () => {} };` – jabaa Aug 29 '23 at 16:26
  • "*This creates an object with a single property bar that is an arrow function and assigns it to foo.*" it's **not** an arrow function. It's (almost entirely) a regular function. The only difference is that it's not constructable. – VLAZ Aug 29 '23 at 16:27
  • @jabaa Are you sure about `{ bar: function () {} }` ? Try `let foo = { bar () {} }; let x = new foo.bar();` You should get "TypeError: x.foo is not a constructor" which you only get with arrow functions, not normal functions. – nwayve Aug 29 '23 at 16:31
  • "*which you only get with arrow functions*" and method definitions – VLAZ Aug 29 '23 at 16:32
  • That's what the documentation says. `bar () {}` is a shorthand for `bar: function () {}` – jabaa Aug 29 '23 at 16:32
  • I guess also generator functions. – VLAZ Aug 29 '23 at 16:35
  • I should rtfm before commenting XP Seems odd to have a "regular function" but not act as a regular function in that it's not constructable. Thanks for all the replies and link to the documentation. I figured it was shorthand but didn't connect it to `let a = 'a'; let b = { a };` shorthand. – nwayve Aug 29 '23 at 16:37
  • 1
    But it's not really related to `{ a }`. Well, the relation is that both are part of object initialiser syntax but by that definition `:` is also the same thing. As for "*Seems odd to have a "regular function" but not act as a regular function in that it's not constructable*" it's exceptionally rare that a callable property of an object also needs to be usable as constructor. When defining actual methods, then in all sensible cases I can think of you'd *not* want them callable with `new`. As that's almost assuredly a mistake. And if it's not, it's not really a method you have. – VLAZ Aug 29 '23 at 16:40
  • It's almost like an "anonymous class object instance" declaration? It behaves similarly. `class Foo { bar() {} }` and `let foo = new Foo(); foo.bar(); /* fine */ new foo.bar(); /* TypeError: not a constructor */` Which feels like: `let foo = { bar () {} };` – nwayve Aug 29 '23 at 16:54

0 Answers0