Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new object within namespace javascript

I'm trying to create a function within a namespace that will get me a new object instance.

I get syntax error trying to do the following:

var namespace = {
    a : function(param){
        this.something = param;
    },
    a.prototype.hi = function(){
        alert('hi');
    },

    b : function(){
        var t = new a('something');
    }
};

What is the correct syntax for doing this? Is it not possible to do within the namespace object? I don't want to declare the namespace first. Thanks

like image 349
JavaKungFu Avatar asked Nov 28 '25 22:11

JavaKungFu


1 Answers

I don't want to declare the namespace first.

You can do weird things like this:

var namespace = {
    init: function() { 
        a.prototype.whatever = function(){};
    },
    a: function(x) {
        this.x = x;
    }  
}
namespace.init();
var myA = new namespace.a("x");

But why not try the module pattern if you want to encapsulate everything? It's way cleaner:

var namespace = (function() {
     function a() {};
     function b(name) {
          this.name = name;
     };
     b.prototype.hi = function() {
          console.log("my name is " + this.name);
     }
     return {
          a: a,
          b: b
     }
})();
like image 103
Jamund Ferguson Avatar answered Dec 01 '25 10:12

Jamund Ferguson