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

2
  • Duplicate. See this SO answer for a way of doing it: stackoverflow.com/questions/7137860/… Commented Dec 3, 2012 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. Commented Dec 3, 2012 at 16:18

3 Answers 3

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
     }
})();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I think I will refactor to use the module pattern.
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() { ... }

2 Comments

I'm not sure what your comment means "no code" - that's clearly not true.
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!
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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.