I've seen a number of approaches to creating your own namespaces in JS, but it does get a bit confusing.
We make use of JQuery and in one project we recently got involved with I noticed that developers used this approach:
var myObject = new function ($){
var localVar = 1,
init = function(){
...
},
return {
init: init
}
}
- Why the use of 'new' function
- Why pass in the $ into this new function?
- Why this form of return?
In another project we used the following approach:
$.companyName = {
textNotFound: "The search returned no results",
search: {
orders: null,
stock: null
}
}
$.companyName.search.orders = function(param1,...){
...
}
$.companyName.search.stock = function(param1,...){
...
}
The usage scenario would look like this:
var orders = $.companyName.search.orders(...);
if (orders == null){
alert($.companyName.textNotFound);
}
else{
...
}
Is this second method not advisable and the first should be used instead? Or, should we be authoring JQuery plugins? (I wouldn't think so, because this is site specific functionality)
Thanks,
Jacques