Best practices for JQuery namespaces + general purpose utility functions
What are some current "rules of thumb" for implementing JQuery namespaces to host general purpose utility functions?
I have a number of JavaScript utility methods scattered in various files that I'd like to consolidate into one (or more) namespaces. What's the best way to do this?
I'm currently looking at two different syntaxes, listed in order of preference:
//******************************
// JQuery Namespace syntax #1
//******************************
if (typeof(MyNamespace) === "undefined")
{
MyNamespace = {};
}
MyNamespace.SayHello = function ()
{
alert("Hello from MyNamespace!");
}
MyNamespace.AddEmUp = function (a, b)
{
return a + b;
}
//******************************
// JQuery Namespace syntax #2
//******************************
if (typeof (MyNamespace2) === "undefined")
{
MyNamespace2 =
{
SayHello: function ()
{
alert("Hello from MyNamespace2!");
},
AddEmUp: function (a, b)
{
return a + b;
}
};
}
Syntax #1 is more verbose but it seems like it would be easier to maintain down the road. I don't need to add commas between methods, and I can left align all my functions.
Are there other, better ways to do this?
For jQuery plugins and such the pattern is to use $.fn.myPlugin
if you want it to be available on elements, and $.whatever
if you just want to use the namespace. I recommend reading the official Plugins Authoring document and these articles.
But jQuery aside, the easiest way to namespace your utils would be along these lines:
var utils = window.utils || {};
utils.method = function(){};
The basics of namespacing in JS hasn't really changed lately - You should check out snook's article, DED's elegant approach and this SO question.
The main advantage of using a self-invoked function to declare namespaces is you can execute stuff privately before returning the object. Also, the object will be ready for auto-complete by your console, which you'll miss on the $
namespace because jQuery returns a function rather than an object.
为了记录,我最终使用了第一种语法:
$(function ()
{
//********************************
// PREDIKT NAMESPACE
//********************************
if (typeof (Predikt) === "undefined")
{
Predikt = {};
}
//********************************
// PREDIKT.TIMER NAMESPACE
//********************************
if (typeof (Predikt.Timer) === "undefined")
{
Predikt.Timer = {};
}
Predikt.Timer.StartTimer = function ()
{
return new Date().getTime();
};
Predikt.Timer.EndTimer = function ()
{
return new Date().getTime();
};
});
链接地址: http://www.djcxy.com/p/49544.html
上一篇: 如何控制Excel中各个饼图段的颜色?