By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,341 Members | 1,726 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,341 IT Pros & Developers. It's quick & easy.

JavaScript Namespace

Expert Mod 5K+
P: 9,731
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:
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <body>
  4. <script type="text/javascript">
  5. Type.registerNamespace("MyNamespace");
  7. MyNamespace.Foo = function(firstNumber,secondNumber){
  8.   this.a = firstNumber; //"a" is now a property of the Foo Object
  9.   this.b = secondNumber;//"b" is now a property of the Foo Object
  10. };
  11. MyNamespace.Foo.prototype = {
  12.     Add: function(){return this.a + this.b;},
  13.     Divide: function(){return this.a/this.b;},
  14.     Multiply: function(){return this.a * this.b;}
  15. };
  16. MyNamespace.Foo.registerClass('MyNamespace.Foo');
  18. var MyNamespace.instanceOfFoo = new Foo(2,3);
  19. document.write(instanceOfFoo.Multiply());
  20. document.write("<br />");
  22.  </script>
  24. </body>
  25. </html>
From what I understand, the Type.registerNamespace method to creates a namespace where I can place my classes required in my project.

If I remove the Namespace, it works fine:
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <body>
  4. <script type="text/javascript">
  6. Foo = function(firstNumber,secondNumber){
  7.   this.a = firstNumber; //"a" is now a property of the Foo Object
  8.   this.b = secondNumber;//"b" is now a property of the Foo Object
  9. };
  10. Foo.prototype = {
  11.     Add: function(){return this.a + this.b;},
  12.     Divide: function(){return this.a/this.b;},
  13.     Multiply: function(){return this.a * this.b;}
  14. };
  16. var instanceOfFoo = new Foo(2,3);
  17. document.write(instanceOfFoo.Multiply());
  18. document.write("<br />");
  21. </script>
  23. </body>
  24. </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,

Feb 20 '09 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 9,731
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....which is proving very difficult to understand.
Feb 20 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.