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
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
- Duplicate. See this SO answer for a way of doing it: stackoverflow./questions/7137860/… – Eli Gassert Commented Dec 3, 2012 at 16:15
- Thanks Eli - I knew there had to be a simple way to do this, seems very mon to me. Unfortunately I have to do some code refactoring now but I don't think it will be too bad. – JavaKungFu Commented Dec 3, 2012 at 16:18
3 Answers
Reset to default 7I 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
}
})();
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() { ... }
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'