I have been reading a bunch of posts, questions, and articles on the use of the with
keyword in JavaScript. Some of the articles warn against the use of Javascript's with
keyword, so I'd like to know if my use is appropriate.
Most of my programming experince is in C# and Java, so when creating related objects namespacing them made sense to me.
The approach I am trying is to first create the root namespace as a globally accessible object. The objects members are the first level namespaces which are also objects.
When to add object to the namespace, I use the Javascript with
keyword to make the members of the argument locally accessible withing the scope of the with. As you move through the namespace, you nest with
s and set the argument to the namespace to be entered.
Here is an example:
var Namespace = {
SubNamespace1: {},
SubNamespace2: {}
}
with (Namespace) {
with (SubNamespace1) {
SubNamespace1.FirstClass = {
foo: function() {
SecondClass.bar();
},
bar: function() {
SecondClass.foo();
}
},
SubNamespace1.SecondClass = {
foo: function() {
FirstClass.bar();
},
bar: function() {
FirstClass.foo();
}
}
}
with (SubNamespace2) {
SubNamespace2.FirstClass = {
foo: function() {
SecondClass.bar();
},
bar: function() {
SecondClass.foo();
}
},
SubNamespace2.SecondClass = {
foo: function() {
FirstClass.bar();
},
bar: function() {
FirstClass.foo();
}
}
}
}