3D-kreativ
3D-kreativ

Reputation: 9301

Trying to understand the difference of objects in javascript

In the code examples below, I understand how alternative 1 and 2 work, but Im trying to understand the third alternative. What kind of object is this and why does it start with a bracket before the function like this: (function and Why does it end with a double bracket like this: (). Just curious and would like to know what is what and the difference?

Alternative 1: (Object Literals)

var something = {
 rows: 12;
 cols: 6;
  };

Alternative 2: (Function Objects)

var something = function(x,y) {
    return x + y;
}

Alternative 3: ??

var something = (function() {
    var settings = {
    rows : 10,
    cols : 3,
    number : 2
    };
    })();

Upvotes: 0

Views: 42

Answers (2)

attila
attila

Reputation: 2219

Alternative 3 sets your "something" variable to the return of the function. () actually executes the function.

I will use something from MDN to show the benefits with closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

var Counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };   
})();

alert(Counter.value()); /* Alerts 0 */
Counter.increment();
Counter.increment();
alert(Counter.value()); /* Alerts 2 */
Counter.decrement();
alert(Counter.value()); /* Alerts 1 */

Upvotes: 1

Ashutosh Upadhyay
Ashutosh Upadhyay

Reputation: 481

In your code, alternative 3 will leave undefined in something variable, reason being your function is not returning any value.

A very good link already posted above by @Felix. This is basically an IIFE which is invoked immediately and return value of that function would be assigned to something variable.

One of the key goal in such pattern typically is to hide some state in a closure. Any variables defined in the function would make the state. These variables would be accessible to the functions in the returned object but not to the outside world.

Upvotes: 0

Related Questions