Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Advantages of object literal

I've read that rather than simply writing a bunch of functions, I should use object literal.

Can someone explain what the advantages of object literal are with examples, because I don't understand thus far.

Thanks

like image 288
Jourkey Avatar asked Oct 21 '09 11:10

Jourkey


People also ask

What is the advantages of using object literals?

Advantage of Object LiteralIt provides a shorter syntax for creating/initializing properties from variables (Property Shorthand). It provides a shorter syntax for defining function methods. It enables the ability to have computed property names in an object's literal definition.

What is the use of object literals in JavaScript?

An object literal in JavaScript allows us to create plain JavaScript objects. It consists of a list of key-value pairs, each separated by a comma and wrapped inside curly braces. In this tutorial let us learn how to create objects using object Literal with examples.

What is difference between object and object literal in JavaScript?

Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.

What is the syntax for an object literal?

Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.


2 Answers

As Russ Cam said, you avoid polluting the global namespace, which is very important in these days of combining scripts from multiple locations (TinyMCE, etc.).

As Alex Sexton said, it makes for good code organisation as well.

If you're using this technique, I'd suggest using the module pattern. This still uses object literals, but as the return value from a scoping function:

var MyThingy = (function() {      function doSomethingCool() {         ...     }      function internalSomething() {         ....     }      function anotherNiftyThing() {         // Note that within the scoping function, functions can         // call each other direct.         doSomethingCool();         internalSomething();     }      return {         doSomethingCool: doSomethingCool,         anotherNiftyThing: anotherNiftyThing     }; })(); 

External use:

MyThingy.doSomethingCool(); 

The scoping function is wrapped around all of your functions, and then you call it immediately and store its return value. Advantages:

  • Functions are declared normally and therefore have names. (Whereas with the {name: function() { ... }} format, all of your functions are anonymous, even though the properties referencing them have names.) Names help tools help you, from showing call stacks in a debugger, to telling you what function threw an exception. (2015 Update: The latest JavaScript specification, ECMAScript 6th edition, defines a large number of ways the JavaScript engine must infer a function's name. One of those is when the function is assigned to a property as in our {name: function() { ... }} example. So as engines implement ES6, this reason will go away.)
  • Gives you the freedom of having private functions only used by your module (such as my internalSomething above). No other code on the page can call those functions; they're truly private. Only the ones you export at the end, in the return statement, are visible outside the scoping function.
  • Makes it easy to return different functions depending on environment, if the implementation just changes completely (such as IE-vs-W3C stuff, or SVG vs. Canvas, etc.).

Example of returning different functions:

var MyUtils = (function() {     function hookViaAttach(element, eventName, handler) {         element.attachEvent('on' + eventName, handler);     }      function hookViaListener(element, eventName, handler) {         element.addEventListener(eventName, handler, false);     }      return {         hook: window.attachEvent ? hookViaAttach : hookViaListener     }; })();  MyUtils.hook(document.getElementById('foo'), 'click', /* handler goes here */); 
like image 151
T.J. Crowder Avatar answered Sep 18 '22 03:09

T.J. Crowder


Using an object literal (a.k.a. object literal pattern) will not pollute the global namespace as severely as using many functions declared globally will, and also helps to organise code in a logical fashion

For example, this object literal

var obj = {               find : function(elem) { /* find code */ },               doSomething: function() { /* doSomething code */ },               doSomethingElse: function() { /* doSomethingElse code */ }           } 

compared to

function find(elem) { /* find code */ }, function doSomething() { /* doSomething code */ }, function doSomethingElse() { /* doSomethingElse code */ } 

will create only one property on the global object compared to three. You can then easily use the functions like so

obj.doSomething(); 
like image 27
Russ Cam Avatar answered Sep 18 '22 03:09

Russ Cam