简体   繁体   中英

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
    };
    })();

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 */

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM