0

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 withs 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();
            }
        }
    }
}
Isioma Nnodum
  • 1,318
  • 13
  • 13
  • 2
    Using `with` is not recommended. [with Statement Considered Harmful](http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/). –  May 25 '13 at 05:10
  • 2
    `with` will throw an error in ES5 strict plus it's slooow. Better not to use it. Can't you just use the full path? Or maybe a module pattern? – elclanrs May 25 '13 at 05:13
  • 1
    Give [this](http://addyosmani.com/blog/essential-js-namespacing/) a read, it might help you out with a solid namespace setup – JayMoretti May 25 '13 at 05:50

0 Answers0