Javascript Object Literal


/ Published in: JavaScript
Save to your folder(s)

In object literal notation, an object is described as a set of comma-separated name/
value pairs enclosed in curly braces ({}). Names inside the object may be either strings or identifiers that are followed by a colon. There should be no comma used after the final name/value pair in the object as this may result in errors.


Copy this code and paste it in your HTML
  1. var myModule = {
  2. myProperty: 'someValue',
  3. // object literals can contain properties and methods.
  4. // here, another object is defined for configuration
  5. // purposes:
  6. myConfig: {
  7. useCaching: true,
  8. language: 'en'
  9. },
  10. // a very basic method
  11. myMethod: function () {
  12. console.log('I can haz functionality?');
  13. },
  14. // output a value based on current configuration
  15. myMethod2: function () {
  16. console.log('Caching is:' + (this.myConfig.useCaching) ? 'enabled' : 'disabled');
  17. },
  18. // override the current configuration
  19. myMethod3: function (newConfig) {
  20. if (typeof newConfig == 'object') {
  21. this.myConfig = newConfig;
  22. console.log(this.myConfig.language);
  23. }
  24. }
  25. };
  26. myModule.myMethod(); // I can haz functionality
  27. myModule.myMethod2(); // outputs enabled
  28. myModule.myMethod3({
  29. language: 'fr',
  30. useCaching: false
  31. }); // fr

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.