javascript - What type of pattern does this JS adhere to? -


i came across code similar recently,

// simplified example.. var application =      {         membervar1: null,         membervar2: null,          initialize: function ()         {             application.membervar1 = 'foo';             application.membervar2 = 'bar';              console.log("initializing..");              application.getmembervars();         },         getmembervars: function ()         {             console.log(application.membervar1 + ' ' + application.membervar2);             }     };  $(application.initialize); 

what name of pattern/method/style? utilizing oop principles without using style i've seen before, such prototyping. benefits of style opposed other popular ones?

it's simple one-off object literal that's being created... can contain functions... perhaps that's threw you.

the last line merely passes application.initialize function jquery $(document).ready callback function

in light of comments below, code (and how can write lot shorter/easier)

$(function() {     console.log("initializing..");     console.log("foo bar");//replace variables declare @top of anon. function if want }); 

as module (you can find out more module pattern here):

var application = (function() {     var membervar1, membervar2,     getmembervars = function()     {         return membervar1 + ' ' + membervar2;     };     return {init: function()     {         membervar1 = 'foo';         membervar2 = 'bar';         console.log('initializing...');         console.log(getmembervars());     }}; }()); $(application.init); 

application object literal, 1 property (init): function that, because declared within scope of iife, has access variables local scope. that's magic of closures you. can add getters , setters member vars, too:

var application = (function() {     var membervars = {},//turned object literal...     getmembervars = function(all)     {         var i;         if(typeof === 'string' || typeof === 'number')         {             return membervars[all];         }         = [];         (i in membervars)         {             if (membervars.hasownproperty(i))             {                 all.push(membervars[i]);             }         }         return all;//or all.join(' '), please     },     = function(name)     {          return typeof name === 'undefined' ? name : membervars[name];      },     set = function(name, val)     {         membervars[name] = val;     };     return {init: function()     {         membervars.one = 'foo';         membervars.two = 'bar';         console.log('initializing...');         console.log(getmembervars().join(' '));     },     get: get,     set: set};//just add getter , setter here }()); 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -