JavaScript Namespace Declaration

后端 未结 8 1873
既然无缘
既然无缘 2020-12-07 15:09

I created a javascript class as follow:

var MyClass = (function() {
   function myprivate(param) {
      console.log(param);
   }

   return {
      MyPublic         


        
8条回答
  •  时光说笑
    2020-12-07 15:25

    YUI has a nice method for declaring namespaces

    if (!YAHOO) {
            var YAHOO = {};
    }
    
    YAHOO.namespace = function () {
        var a = arguments,
            o = null,
            i, j, d;
        for (i = 0; i < a.length; i = i + 1) {
            d = ("" + a[i]).split(".");
            o = YAHOO;
            for (j = (d[0] == "YAHOO") ? 1 : 0; j < d.length; j = j + 1) {
                o[d[j]] = o[d[j]] || {};
                o = o[d[j]];
            }
        }
        return o;
    }
    

    Place it above any function that you want to namespace like this:

    YAHOO.namespace("MyNamespace.UI.Controls")
    
    MyNamespace.UI.Controls.MyClass = function(){};
    MyNamespace.UI.Controls.MyClass.prototype.someFunction = function(){};
    

    This method is actually stand-alone and can easily be adapted to your application. Just find and replace "YAHOO" with your application's base namespace and you'll have something like MyOrg.namespace. The nice thing with this method is that you can declare namespaces at any depth without having to create object arrays in between, like for "UI" or "Controls"

提交回复
热议问题