0

Seems like it works

console.log({name: 'fred', age: 65}.name);  //fred
console.log({name: 'fred', age: 65}.age);   //65

until I try to use a method

{greet(){console.log('hello');}}.greet();   //Uncaught SyntaxError: unexcted token: '{'

Assigning an identical object literal to a const and then invoking its method works

const greeter = {greet(){console.log('hello');}};
greeter.greet();                                    //hello 

Is such usage not allowed?

1
  • You can assign an anonymous object to a named var and use that. Commented Dec 11, 2022 at 10:47

1 Answer 1

1

You just lack () to properly call the anonymous object

({ greet() { console.log('hello'); } }).greet() // hello
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.