JQuery名称空间+通用工具功能的最佳实践 [英] Best practices for JQuery namespaces + general purpose utility functions
问题描述
用于实现 JQuery名称空间以托管通用工具功能的当前经验法则" 是什么?
What are some current "rules of thumb" for implementing JQuery namespaces to host general purpose utility functions?
我有许多JavaScript实用程序方法分散在各种文件中,我想将它们合并到一个(或多个)命名空间中.最好的方法是什么?
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;
}
};
}
语法1较为冗长,但似乎在将来更容易维护.我不需要在方法之间添加逗号,并且可以将所有函数对齐.
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.
还有其他更好的方法吗?
推荐答案
为了记录,我最终使用了第一种语法:
For the record, I ended up using the first syntax:
$(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();
};
});
这篇关于JQuery名称空间+通用工具功能的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!