javascript命名空间的首选技术 [英] Preferred technique for javascript namespacing
问题描述
如果我不开始使用某种命名空间技术,我的代码将变成一团糟。我对编写大型javascript项目相对较新,但在C ++ / java / python等系统编程方面具有丰富的经验。
My code is going to turn into a mess if I don't start using some sort of namespacing technique. I'm relatively new to programming large javascript projects but have significant experience with systems programming in C++/java/python etc.
基本上我正在尝试识别哪个是创建javascript命名空间的首选方法,以及每种方法的优缺点。
Basically I'm trying to identify which is the preferred method for creating javascript namespaces, and what the pros/cons are for each method.
例如,我可以使用以下三种方法之一:
For example I could use either of the following three methods:
var proj.lib.layout = {
"centreElem":
function (elem, W, H){
},
"getAbsolutePosition":
function (elem){
}
};
OR
var proj.lib.layout = {};
(function(){
var l = proj.lib.layout;
l.centreElem = function (elem, winW, winH){
..
}
l.getAbsolutePosition = function (elem){
..
}
})();
OR
var proj.lib.layout = new function(){
function centreElem(elem, W, H){
..
}
function getAbsolutePosition(elem){
..
}
this.centreElem = centreElem;
this.getAbsolutePosition = getAbsolutePosition;
} ();
还有其他方法可以做得太明显,但这些是我见过的第一个想到。任何人都可以说有一种最好的技术,或者至少指向一些利弊,我可以从中评估哪种方式最适合我?
There are other ways to do it too obviously, but these were the first that I've seen and thought of. Can anyone say there is a "best" technique, or at least point me towards some pros/cons from which I can evaluate which is best for me?
推荐答案
请注意,您必须先创建所有中间对象,然后才能分配到这样的子对象:
Note that you have to create all the intermediary objects before you can assign to a sub-object like that:
window.one.two.three = {}; // fails
window.one = { two: { three: {} } };
考虑编写命名空间方法,以便统一命名空间代码。例如:
Consider writing a namespacing method, so you can unify your namespace code. For example:
window.proj = {};
// n - {String} - A string representing a namespace to create on proj
// returns an object you can assign values to
window.proj.namespace = function(n) { /* ... */ };
(function(NS) {
NS.myMethod = function() {};
NS.myOtherMethod = function() {};
NS.myProperty = "FOO";
})(proj.namespace('lib.layout'));
assert(proj.lib.layout.myProperty === "FOO");
这篇关于javascript命名空间的首选技术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!