Avoiding the Javascript Keyword With

Javascript is the most used language for client side web development, due to its presence in virtually all modern browsers. Despite being easy to use, Javascript has a few issues that make it difficult to use and maintain.

One example is the "with" keyword. It was created to make it easier to write code in the language, which makes sense if we consider that this is a language well tailored to scripts. Here is a simple example of how it can be used.

Suppose that we have an object with several methods that we want to call in sequence. The with keyword can be a handy way to do this, using the following syntax:

var myObj;
// instead of this
myObj.method1();
myObj.method2();
myObj.method3();
// we can use the 'with' keyword
with (myObj) {
   method1();
   method2();
   method3();
}

While this may seem like a good idea at first, in practice we found that there a lot of issues that may be caused by the inadequate use of with. First, it may lead to subtle bugs.

The reason is that the with keywords changes the way that properties in an object are searched. The properties are first searched in the object, but if not found there then Javascript can select a global property, for example. This is almost never what we want, and it can lead to very subtle errors.

Another issue, although a less serious one, is related to performance. We want to avoid the performance penalty of looking up properties in places of other than the object itself. When using the dot notation, Javascript knows where the property is located, so it will stop searching as soon as possible. However, using the 'with' keyword will have Javascript searching for properties in the global namespace, even if this is not what we want.

As we see, the 'with' keyword is not really a great idea from the point of view of maintenance either. If an object changes, the fact the we are using a with keyword may mask an error, and complicate testing. The keyword essentially creates a dynamic scope, that changes how the software works depending on what variables are available in containing scopes. It is common knowledge that a lexical scope is much easier to maintain than a dynamic scope, and for similar reasons we should avoid the use of the 'with' keyword.

Tags: programming, javascript
Article created on 2012-09-14 20:48:35

Post a comment