Sometime ago I heard that it was good practice to wrap your code in a big object to serve as a namespace in order to reduce global namespace cluttering and to facilitate library export, so I tried this.
var wrapper = {
foo: function(){
return 42;
},
bar: this.foo()
};
It fails, claiming that "foo is not defined". Calling methods before finishing the object declaration is probably bad, so I moved bar, and it worked.
var wrapper = {
foo: function(){
return 42;
},
};
wrapper.bar = wrapper.foo();
I feel that this can become kind of ugly, especially with nested namespaces and such, so are there any workarounds that don't make it hard to see all of the wrapper's members at once?
The problem is that this
is going to equal the global context. You need to access the function like so:
var wrapper = {
foo: function(){
return 42;
},
bar: null,
init : function() {
// all initialization code goes here
wrapper.bar = wrapper.foo();
}
};
wrapper.init();
This method is great for organizing your code into logical chunks so you and future developers can easily find what you are looking for in your javascript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With