When to use global variable in jQuery? -


i need set dateformat few datepickers.

what best way define dateformat?

defining simple method

function dateformat() {     return 'yy-mm-dd'; }  

or global variable like

dateformat = 'yy-mm-dd' 

?

ok, according your comment:

@markushofmann, reply. can please me out when use global variables in jquery example if any?

…i've been looking information use of global variables jquery.

here i'll sum i've found. may find sources @ end of answer.

here go:

normally define global variables omitting var (like did in question):

dateformat = 'yy-mm-dd'; 

but!!! omitting var generates implicit global, bad thing , generate error in strict mode.

however, if need generate global variables in production code (which should avoided) declare them explicitly:

window.dateformat = 'yy-mm-dd'; 

 
can use above approach create global vars inside namespace in window / jquery object:

window object:

window.mynamespace = {     dateformat = 'yy-mm-dd',     ... }; 

jquery object:

$.mynamespace = {     dateformat = 'yy-mm-dd',     ... }; 

but keep in mind careful naming namespace, there may occur naming conflicts if there equal namespace form plugin or so. i'd recommend encapsulate globals within single global namespace makes independent of jquery , doesn't clutter namespace.

encapsulate globals within single global namespace:

var mynamespace = {}; // global object container mynamespace.dateformat = 'yy-mm-dd'; 

you may use closure define globals or private member variables.

to make long story short: it best practice avoid globals.

 

sources:

  1. https://stackoverflow.com/a/3352033/2493918
  2. https://stackoverflow.com/a/2895772/2493918
  3. how cleanly deal global variables?
  4. http://www.javascripttoolbox.com/bestpractices/#namespace
  5. http://jibbering.com/faq/notes/closures/
  6. http://www.crockford.com/javascript/private.html
  7. https://stackoverflow.com/search?q=namespace+javascript+global

edit:

i'd add 1 more thing answer: when write plugins jquery put code inside of immediately invoked function expression (iife) , pass function jquery, , name parameter $. closure allows have own private variables , protects jquery $ alias:

(function( $ ){      ...your code here...  })( jquery ); 

ben alman has a post on site provides more information iife.

there's iife related question great answers worth reading here on stackoverflow:
using 'window', 'document' , 'undefined' arguments in anonymous function wraps jquery plugin


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -