I need to set the dateFormat
for a few datepickers.
What is the best way to define the dateFormat
?
Defining a simple method like
function dateFormat() {
return 'yy-mm-dd';
}
or Global variable like
dateFormat = 'yy-mm-dd'
?
I need to set the dateFormat
for a few datepickers.
What is the best way to define the dateFormat
?
Defining a simple method like
function dateFormat() {
return 'yy-mm-dd';
}
or Global variable like
dateFormat = 'yy-mm-dd'
?
Ok, according to your comment:
@MarkusHofmann, Thanks for your reply. Can you please help me out when to use global variables in jquery with an example if any?
…I've been looking for information about the use of global variables with jQuery.
Here I'll sum up what I've found. You may find the sources at the end of this answer.
Normally you define global variables by just omitting var
(like you did in your question):
dateFormat = 'yy-mm-dd';
BUT!!! Omitting var
generates an implicit global, which is a bad thing to do and would generate an error in strict mode.
However, if you need to generate global variables in production code (which should be avoided) always declare them explicitly:
window.dateFormat = 'yy-mm-dd';
You can use the above approach to create global vars inside a namespace in the window / jQuery object:
Window Object:
window.myNameSpace = {
dateFormat = 'yy-mm-dd',
...
};
jQuery Object:
$.myNameSpace = {
dateFormat = 'yy-mm-dd',
...
};
But keep in mind to be careful with naming the namespace, as there may occur naming conflicts if there is another equal namespace form a plugin or so. I'd recommend to encapsulate the globals within a single global namespace as this makes it independent of jQuery and it doesn't clutter its namespace.
Encapsulate the globals within a single global namespace:
var MyNameSpace = {}; // The global object container
MyNameSpace.dateFormat = 'yy-mm-dd';
You may also use a Closure to define globals or Private Member Variables.
To make this long story short: It is a best practice to avoid globals.
I'd like to add one more thing to my answer: When I write plugins for jQuery I put all code inside of an Immediately Invoked Function Expression (IIFE) and then pass the function jQuery, and name the parameter $. This closure allows you to have your own private variables and protects the jQuery $
alias:
(function( $ ){
...YOUR CODE HERE...
})( jQuery );
Ben Alman has a good post on his site that provides more information about IIFE.
There's also a IIFE related question with great answers worth reading here on StackOverflow:
Using 'window', 'document' and 'undefined' as arguments in anonymous function that wraps a jQuery plugin