frontend - Objects as variable containers in JavaScript -


recently saw in code project i'm working on...

var domobjects = {   $body: $('body'),   $somediv: $('.some-div'),   $someotherdiv: $('.some-other-div') }  var constants = {   const_one: 'some value',   const_two: 'some value',   const_three: 'some value' } 

as may notice code intents replace code this:

var $body = $('body'),     $somediv = $('.some-div'),     $someotherdiv = $('.some-other-div');  var const_one = 'some value',     const_two = 'some value',     const_three = 'some value'; 

the idea behind wrap variables in more "semantic" object easier use, have doubts create object cosmetic reasons.

  • it ok?
  • there real advantage if declarations way?
  • there disadvantage?

it's fine: javascript lets put values inside of object, means can use js objects "containers" things common variables or constants.

it's matter of personal preference. construction easier pass around, don't "requery" things $body or $document, can hide what's in object, don't know how "room" function input taking up.

is problem? maybe, maybe not, that's whoever writes/uses code. question (beyond "is okay" part, totally is) matter of opinion, guided code style guides, , considerations how pack commonly used references.

there 1 instance style makes difference, , that's when unrolling switches. instance:

function(input) {   var = "cat",       b = "cow",       c = "goldfish";   console.log("testing multiple case identities...");   switch(input) {     case "small": return a;     case "large": return b;     case "aquatic":      case "fish": return c;   };   return false; } 

instead of check-by-check, can immediate:

var values = {   "small": generatesmallanimal,   "large": generatelargeanimal,   "aquatic": generatefish   "fish": generatefish };  function(input) {   console.log("direct jump...");   return values[input](); } 

done, no multiple case checks, immediate jump right thing.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -