Trying to understand the difference of objects in javascript -


in code examples below, understand how alternative 1 , 2 work, im trying understand third alternative. kind of object , why start bracket before function this: (function , why end double bracket this: (). curious , know what , difference?

alternative 1: (object literals)

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

alternative 2: (function objects)

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

alternative 3: ??

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

alternative 3 sets "something" variable return of function. () executes function.

i use mdn show benefits 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 */ 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -