Skip to content
Advertisement

defining getters/setters in an object literal with a self-invoking function javascript

When defining an object literal its possible to use a self-invoking function so the function has access to private variables,

JavaScript

But is it possible to do the same thing with a getter/setter in an object literal?

JavaScript

Advertisement

Answer

[edit 2022] A pretty old answer.

More actual: you can create a factory function. In the snippet the factory creates an object with (get and set) access (through the closure) to a private variable.

JavaScript

The old answer:

Not really. You can also create an Immediately Invoked Function Expression (IIFE) for obj though:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement