3

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

JavaKungFu
  • 1,264
  • 2
  • 11
  • 24
  • Duplicate. See this SO answer for a way of doing it: http://stackoverflow.com/questions/7137860/javascript-namespace-declaration-with-function-prototype – Eli Gassert Dec 03 '12 at 16:15
  • Thanks Eli - I knew there had to be a simple way to do this, seems very common to me. Unfortunately I have to do some code refactoring now but I don't think it will be too bad. – JavaKungFu Dec 03 '12 at 16:18

3 Answers3

7

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
     }
})();
Chase Sandmann
  • 4,795
  • 3
  • 30
  • 42
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
0

A javascript namespace is an object so you can only use key: value couples but no code (as you do with : a.prototype.hi = function() {...}).

You should thus separate that in two : declaration and then code :

var namespace = {
    a : function(param){
        this.something = param;
    },
    b : function(){
        var t = new a('something');
    }
};

namespace.a.prototype.hi : function() { ... }
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
  • I'm not sure what your comment means "no code" - that's clearly not true. – JavaKungFu Dec 03 '12 at 16:19
  • Yes, probably is it badly formulated, here it is the "key" `a.prototype.hi` which is impossible in a javascript object, but in the value you can add whatever code you want! – Samuel Caillerie Dec 03 '12 at 16:20
0

I do not exactly know what you want, but this works:

var namespace = {

    a: function() {

        function a() {

        }

        a.prototype.hi = function() {
            console.log("hi");
        }

        return new a;

    }

}

var obj = new namespace.a();
obj.hi()

// -> 'hi'
Amberlamps
  • 39,180
  • 5
  • 43
  • 53