建议使用JavaScript中的命名空间技术?表演者?要注意的问题? [英] Namespacing technique in JavaScript, recommended? performant? issues to be aware of?
问题描述
在项目中,我正在研究我正在构造我的代码如下
In a project I am working on I am structuring my code as follows
MyLib = {
AField:0,
ASubNamespace:{
AnotherField:"value",
AClass:function(param) {
this.classField = param;
this.classFunction = function(){
// stuff
}
}
},
AnotherClass:function(param) {
this.classField = param;
this.classFunction = function(){
// stuff
}
}
}
依此类推,例如:
var anInstance = new MyLib.ASubNamespace.AClass("A parameter.");
这是实现命名空间的正确方法吗?是否有性能方面的问题,如果有的话,有多大?当我嵌套得更深时,性能下降是否会叠加?使用此结构时,我还有其他需要注意的问题吗?
Is this the right way to go about achieving namespacing? Are there performance hits, and if so, how drastic? Do performance degradations stack as I nest deeper? Are there any other issues I should be aware of when using this structure?
我关心每一个性能,因为它是用于实时图形的库,所以我非常认真地考虑所有开销.
I care about every little bit of performance because it's a library for realtime graphics, so I'm taking any overhead very seriously.
推荐答案
在将代码构造为大型巨型对象属性层次结构时,有时会遇到MyNamespaceObj.prop1
尚不适用于MyNamespaceObj.prop2
的问题.还有一个事实,就是您经常在整个代码中多次键入完全限定的名称.
When you structure your code as a big giant object-property hierarchy, you sometimes have issues where MyNamespaceObj.prop1
isn't available to MyNamespaceObj.prop2
yet. And then there's the fact that you often end up typing fully qualified names a lot throughout the code.
我开始发现我更喜欢做这样的事情:
I'm starting to find I prefer doing something like this:
MyNamespaceObj = (function () {
// lots of code/definitions that have local scope
var internallyDefinedItem1 = function (n) { /* ... */ }
var internallyDefinedItem2 = {
foo: internallyDefinedItem1(532),
bar: totallyPrivateNeverExportedFunction(17)
}
var totallyPrivateNeverExportedVar = 'blahblahblah';
function totallyPrivateNeverExportedFunction (x) {
/* ... */
}
return {
exportedItem1: internallyDefinedItem1,
exportedItem2: internallyDefinedItem2,
...
}
})();
这篇关于建议使用JavaScript中的命名空间技术?表演者?要注意的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!