2010-03-24 3 views
28

ich eine Javascript-Klasse wie folgt erstellt:JavaScript-Namespace Deklaration

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

    return { 
     MyPublic : function(param) { 
     myprivate(param); 
     } 
    }; 
})(); 

MyClass.MyPublic("hello"); 

Der obige Code funktioniert, aber meine Frage ist, wie wenn ich will Namensraum dieser Klasse einzuführen.

Grundsätzlich möchte ich in der Lage sein, die Klasse wie folgt zu nennen:

Namespace.MyClass.MyPublic("Hello World"); 

Wenn ich Namespace.MyClass hinzugefügt, wird es Fehler „Syntaxfehler“ werfen. Ich habe versucht, "window.Namespace = {}" hinzuzufügen und es funktioniert auch nicht.

Dank .. :)

+0

Genaues Duplikat ... http://StackOverflow.com/Questions/881515/Javascript-Namespace-Declaration –

Antwort

43

Normalerweise würde ich empfehlen, dies zu tun (Namespace unter der Annahme definiert ist nicht an anderer Stelle):

var Namespace = {}; 
Namespace.MyClass = (function() { 
    // ... 
}()); 

Ein flexibler, aber komplexer, Ansatz:

var Namespace = (function (Namespace) { 
    Namespace.MyClass = function() { 

     var privateMember = "private"; 
     function myPrivateMethod(param) { 
     alert(param || privateMember); 
     }; 

     MyClass.MyPublicMember = "public"; 
     MyClass.MyPublicMethod = function (param) { 
      myPrivateMethod(param); 
     }; 
    } 
    return Namespace 
}(Namespace || {})); 

Diese Namespace.MyClass wie oben baut, aber ist nicht auf Namespace bereits vorhanden. Es wird deklariert und erstellt es, wenn es nicht bereits existiert. Dadurch können Sie auch mehrere Mitglieder von Namespace parallel in verschiedenen Dateien laden, Lader Reihenfolge spielt keine Rolle.

Weitere: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

+2

+1, nette Annäherung! – CMS

+0

Was bedeutet '(Namespace || {});' am Ende? –

3

Eine prägnante Art und Weise zu tun, was Sie fragen, ist „Namespace“ als Objektliteral wie folgt erstellen:

Diese
var Namespace = { 
    MyClass : (function() { 
     ... rest of your module 
    })(); 
}; 

Konflikte verursachen könnte, wenn man wollte andere Details an den Namespace in anderen Dateien anhängen, aber Sie könnten das umgehen, indem Sie zuerst Namespace erstellen und dann die Member explizit festlegen.

9

YUI hat eine schöne Methode zur Deklaration 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; 
} 

Platz es über jede Funktion, die Sie wie folgt Namespace wollen:

YAHOO.namespace("MyNamespace.UI.Controls") 

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

Diese Methode ist eigentlich stand-alone und kann leicht an Ihre Anwendung angepasst werden. Suchen Sie und ersetzen Sie "YAHOO" mit dem Basis-Namespace Ihrer Anwendung und Sie werden etwas wie MyOrg.namespace haben. Das nette Ding mit dieser Methode ist, dass Sie Namespaces an jeder Tiefe erklären können, ohne Objektarrays dazwischen zu verursachen, wie für "UI" oder "Kontrollen"

2

Bezahlen Sie die namespace library, es ist sehr leicht und einfach zu implementieren .

(function(){ 
    namespace("MyClass", MyPublic); 

    function MyPublic(x){ 
    return x+1; 
    } 
})(); 

Es unterstützt auch

namespace("MyClass.SubClass.LowerClass", ....) 

würde, um die notwendige Objekthierarchie automatisch verschachteln, wenn MyClass, SubClass nicht bereits vorhanden ist.

1

bob.js hat schöne Syntax JavaScript Namensraum zu definieren:

bob.ns.setNs('myApp.myMethods', { 
    method1: function() { 
     console.log('This is method 1'); 
    }, 
    method2: function() { 
     console.log('This is method 2'); 
    } 
}); 
//call method1. 
myApp.myMethods.method1(); 
//call method2. 
myApp.myMethods.method2(); 
0

Namespace-Deklaration in Javascript Automatisierung ist sehr einfach, wie Sie sehen: es

var namespace = function(str, root) { 
    var chunks = str.split('.'); 
    if(!root) 
     root = window; 
    var current = root; 
    for(var i = 0; i < chunks.length; i++) { 
     if (!current.hasOwnProperty(chunks[i])) 
      current[chunks[i]] = {}; 
     current = current[chunks[i]]; 
    } 
    return current; 
}; 

// ----- USAGE ------ 

namespace('ivar.util.array'); 

ivar.util.array.foo = 'bar'; 
alert(ivar.util.array.foo); 

namespace('string', ivar.util); 

ivar.util.string.foo = 'baz'; 
alert(ivar.util.string.foo); 

ausprobieren: http://jsfiddle.net/stamat/Kb5xY/ Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

0

Dies ist das Design-Muster, das ich verwende, die für verschachtelten Namen ermöglicht sowie Räume wie das Hinzufügen auf den Namespace später (auch von einer separaten JS-Datei), so dass Sie nicht verschmutzen den globalen Namensraum:

Beispiel: JsFiddle

(function ($, MyObject, undefined) {  
    MyObject.publicFunction = function() { 
     console.log("public"); 
    }; 

    var privateFunction = function() { 
     console.log("private"); 
    }; 

    var privateNumber = 0; 
    MyObject.getNumber = function() { 
     this.publicFunction(); 
     privateFunction(); 
     privateNumber++; 
     console.log(privateNumber); 
    }; 

    // Nested namespace 
    MyObject.nested = MyObject.nested || {}; 
    MyObject.nested.test = function (text) { 
     console.log(text); 
    };  
}(jQuery, window.MyObject = window.MyObject || {})); 

// Try it 
MyObject.getNumber(); 
MyObject.nested.test('Nested'); 

Hier ist, wie man MyObject von einem anderen hinzuzufügen JavaScript-Datei:

(function ($, MyObject, undefined) { 
    MyObject.newFunction = function() { 
     console.log("Added"); 
    }; 
}(jQuery, window.MyObject = window.MyObject || {})); 
// Pass `jQuery` to prevent conflicts and `MyObject` so it can be added to, instead of overwritten 

Diese Ressource half mir alles über die verschiedenen JS Entwurfsmuster lernen: http://addyosmani.com/resources/essentialjsdesignpatterns/book/

1
(function($){ 

    var Namespace = 
{ 
    Register : function(_Name) 
    { 
     var chk = false; 
     var cob = ""; 
     var spc = _Name.split("."); 
     for(var i = 0; i<spc.length; i++) 
     { 
      if(cob!=""){cob+=".";} 
      cob+=spc[i]; 
      chk = this.Exists(cob); 
      if(!chk){this.Create(cob);} 
     } 
     if(chk){ throw "Namespace: " + _Name + " is already defined."; } 
    }, 

    Create : function(_Src) 
    { 
     eval("window." + _Src + " = new Object();"); 
    }, 

    Exists : function(_Src) 
    { 
     eval("var NE = false; try{if(" + _Src + "){NE = true;}else{NE = false;}}catch(err){NE=false;}"); 
     return NE; 
    } 
} 
    Namespace.Register("Campus.UI.Popup") 
    Campus.UI.Popup=function(){ 
     defaults={ 
      action:'', 
      ispartialaction:'', 
      customcallback:'', 
      confirmaction:'', 
      controltoupdateid:'', 
      width:500, 
      title:'', 
      onsubmit:function(id){ 
       var popupid=id+"_popupholder"; 
       if(this.ispartialaction){ 
        $.ajax({ 
         url:this.action, 
         type:"Get", 
         context:this, 
         success:function(data){ 
          $('#'+id).parents('body').find('form').append("<div id'"+popupid+"'></div>"); 
          var ajaxContext=this; 
          $("#"+popupid).dialog({ 
           autoopen:false, 
           model:true, 
           width:this.width, 
           title:this.title, 
           buttons:{ 
            "Confirm":function(){ 
             if(ajaxContext.customcallback==''){ 
              var popupform=$(this).find("form"); 
              if(popupform.isValid()){ 
               $.post(ajaxContext.confirmaction,popupform.serialize(),function(d){ 
                if(d!='') 
                { 
                 $.each(d.Data,function(i,j){ 
                  switch(j.Operation) 
                  { 
                   case 1: 
                    if($('#'+j.ControlClientID).is("select")) 
                    { 
                     $('#'+j.ControlClientID).val(j.Value); 
                     $('#'+j.ControlClientID).change(); 
                    } 
                    else if($('input[name="'+j.ControlClientID+'"]').length>0) 
                    { 
                     $('input[name="'+j.ControlClientID+'"][value="'+j.Value+'"]').prop("checked",true); 
                    } 
                    break; 
                   case 2: 
                    if($('#'+j.ControlClientID).is("select")) 
                    { 
                     $('#'+j.ControlClientID).append("<option selected='selected' value=\""+j.Value+"\">"+j.Text+"</option>"); 
                    } 
                    else 
                    { 
                     var len=$('input[name="'+j.ControlClientID+'"]').length; 
                     $('#'+j.ControlClientID+"list").append('<li><input type="checkbox" name="'+j.ControlClientID+'" value="'+j.Value+'" id="ae'+j.ControlClientID+len+'"/><label for "ae'+j.ControlClientID+len+'">'+j.Text+'</label>'); 
                    } 
                    break; 
                   case 0: 
                    $('#'+j.ControlClientID).val(j.Value); 
                    breakl 
                   default:break; 
                  } 
                 });                  

                 popupform.parent().dialog("destroy").remove(); 
                 $("#"+ajaxContext.controltoupdateid).change(); 
                } 
               }); 
              } 
             } 
             else 
             { 
              executeByFunctionName(ajaxContext.customcallback,window,new Array()); 
             } 
            }, 
            "Cancel":function(){ 
             $(this).dialog("close"); 
            } 
           } 
          }); 
          $("#"+popupid).dialog("open"); 
          $("#"+popupid).empty().append(data); 
         }, 
         error:function(e) 
         { 
          alert(e); 
         } 
        }); 
       } 
       else 
       { 
        var frm=document.createElement("form"); 
        frm.id="CampusForm"; 
        frm.name="CampusForm"; 
        frm.action=this.action; 
        frm.method="post"; 
        var arr=$($("#"+id).closest("body").find("form")).serializeArray(); 
        $.each(arr,function(i,j){ 
         var hidd=document.createElement("input"); 
         hidd.type="hidden"; 
         hidd.name=j.name; 
         hidd.value=j.value; 
         frm.appendChild(hidd);}); 
        document.appendChild(frm); 
        frm.submit(); 
       } 
      } 
     }, 
     clicksubmit=function(){ 
      var opts=$(this).data("CampusPopup"); 
      opts.onsubmit($(this).attr("id")); 
      return false; 
     }; 
     return 
     { 
      init:function(opt){ 
       var opts=$.extend({},defaults,opt||{}); 
       $(this).data('CampusPopup',opts); 
       $(this).bind("click",clicksubmit); 
      }}; 
    }(); 
    $.extend({CampusPopup:Campus.UI.Popup.init}); 
})(jQuery)