Namespacing technique in JavaScript, recommended? performant? issues to be aware of?

此生再无相见时 提交于 2019-11-30 22:55:14

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,
        ...
    }
})();
Upperstage

I suggest namespacing is a critical part of writing maintainable JavaScript - especially if you work with a team of developers.

Performance issues related to namespacing should be minimal if you compress/minimize your code on the way to production.

Here is an SO discussion of alternative ways to use namespaces.

Namespacing your JavaScript is critical to avoid potential conflicts and overwrites. This is specially true when your JS will land up in foreign environments where external JS can also reside.

With that said, there is a performance hit because of namespacing, simply because the interpreter now has to follow a longer chain to access the required function/property.

For example, something like

  var myProperty;

is accessed a little faster as compared to :

 myNameSpace.module1.myProperty;

I think the difference in speed is not much unless you namespace extremely deeply and the advantage of avoiding potential conflicts is a big plus of namespacing.

But still, it is always good to keep this issue in mind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!