JavaScript Namespace

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    JavaScript Namespace

    So, today I learned how to define classes, create instances of Objects, and use inheritance. I thought I was all set to go and was excited about finally getting something accomplished today (other than just learning stuff).

    Well I didn't get far.

    I'm stuck on Namespaces in JavaScript.

    The following does not work:
    Code:
    <html>
    <body>
     
    <script type="text/javascript">
    Type.registerNamespace("MyNamespace");
    
    MyNamespace.Foo = function(firstNumber,secondNumber){
      this.a = firstNumber; //"a" is now a property of the Foo Object
      this.b = secondNumber;//"b" is now a property of the Foo Object
    };
    MyNamespace.Foo.prototype = {
        Add: function(){return this.a + this.b;},
        Divide: function(){return this.a/this.b;},
        Multiply: function(){return this.a * this.b;}
    };
    MyNamespace.Foo.registerClass('MyNamespace.Foo');
    
    var MyNamespace.instanceOfFoo = new Foo(2,3);
    document.write(instanceOfFoo.Multiply());
    document.write("<br />");
    
     </script>
     
    </body>
    </html>
    From what I understand, the Type.registerNa mespace method to creates a namespace where I can place my classes required in my project.

    If I remove the Namespace, it works fine:
    Code:
    <html>
    <body>
     
    <script type="text/javascript">
    
    Foo = function(firstNumber,secondNumber){
      this.a = firstNumber; //"a" is now a property of the Foo Object
      this.b = secondNumber;//"b" is now a property of the Foo Object
    };
    Foo.prototype = {
        Add: function(){return this.a + this.b;},
        Divide: function(){return this.a/this.b;},
        Multiply: function(){return this.a * this.b;}
    };
    
    var instanceOfFoo = new Foo(2,3);
    document.write(instanceOfFoo.Multiply());
    document.write("<br />");
    
     
    </script>
     
    </body>
    </html>
    Could someone please explain what is going on here?
    Is the Type class part of the Ajax Framework that ASP.NET uses? Or is it a native JavaScript Object?

    Thanks again,

    -Frinny
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Oh, never mind.

    The Type class is part of the Microsoft AJAX Library and this is why my attempts at using the Type class in the w3c "Tryit Editor" isn't working.

    I was attempting to keep things as simple as possible...but Microsoft decided to complicate them further by providing an "easy to use" framework....wh ich is proving very difficult to understand.

    Comment

    Working...