Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

Using prototype - JavaScript Optimization - Part 1

Defining Class Methods :

Let us consider an example.

foo.bar = function() {
    this.foobar2 = function() {
    }
}

Here what happens is, every time an instance of foo.bar is constructed, a new function and closure is created for foo. A closure is just a function that can have free variables with an environment that binds those variables. A closure is created when returning a function object that was created within an execution context of a function call. Unfortunately, closures require an understanding of the mechanism behind them and quite bit of technical detail too. I’ll explain in detail regarding CLOSURES in my next post. Now, getting back to the topic, the above said method of defining a class method is not the efficient way. A preferred approach would be,

foo.bar = function() {
};
foo.bar.prototype.foobar2 = function() {
};

With this approach, no matter how many instances of foo.bar are constructed, only a single function is created for foo, and no closures are created.

Initializing instance variables :

Similar to the function, the variables are also dealt the same way. When you initialize a variable inside the constructor, every time it is called, the variables are re-declared. So a better option would be to place these variable declaration or initialization on the prototype. To be noted, those instance variables whose initial value is dependent on constructor should not be used on prototype. The dependencies may be on the argument of the constructor or some other state at time of construction.

foo.bar.prototype.myVar = 4;
foo.bar.prototype.myBool = true;

To the reader: Comments are welcome regarding correctness of the context. If you are not comfortable with my English, do bear with it, Will improve on the next coming posts.