Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to use anonymous objects in javascript?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Is such usage not allowed?

>Solution :

You just lack () to properly call the anonymous object

({ greet() { console.log('hello'); } }).greet() // hello
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading