JavaScript best practices I

Now that we’ve seen the basic JavaScript concepts, we’ll go through some recommendations to make a good code. These are some practices that should be followed if you want to make a readable and maintainable code. It is based on my knowledge and experience of JavaScript over several years of practical experience:

Read the rest of this entry »

Object Oriented JavaScript III: some tips

We’ve already gone through the basic JavaScript concepts we need to write object oriented code, and we’ve already seen the basic pattern. But here’s a couple of tips that has proven useful many times when writing long and complex JavaScript code.

The curious case of the mutating scope

Ok, now imagine we have some fancy widget in our class and we want to interact with it. There are many widgets which redefine the this keyword to its instance instead of ours. For this case, we might want to be able to access our instance instead of the widget instance. We’ll need to redefine the scope in which the function is being executed. To do so, we can use the following function:

// Creates a new function and returns a reference. This new function has its scope set to 'newScope'
this.setScope = function (originalFn, newScope) {
   return function () { return originalFn.apply(newScope, arguments); };
};

We could just use the apply method on our original function, but I prefer this way since its more comfortable to work with parameters like this.

Be careful when using this, since this is a double-edged sword. By accessing our class scope we have all our data available. But we won’t have the widget’s scope available anymore. So make sure you don’t need to access the widget’s scope before changing the scope of the event handler.

Read the rest of this entry »