views:

124

answers:

2

Hi, I am trying to optimize my program. I think I understand the basics of closure. I am confused about the scope chain though.

I know that in general you want a low scope (to access variables quickly).

Say I have the following object:

var my_object = (function(){

        //private variables
        var a_private = 0;

    return{ //public
             //public variables
             a_public : 1,

             //public methods
             some_public : function(){
                  debugger;
                  alert(this.a_public);
                  alert(a_private);
             };
        };
})();

My understanding is that if I am in the some_public method I can access the private variables faster than the public ones. Is this correct?

My confusion comes with the scope level of this.

When the code is stopped at debugger, firebug shows the public variable inside the this keyword. The this word is not inside a scope level.

How fast is accessing this? Right now I am storing any this.properties as another local variable to avoid accessing it multiple times.

Thanks very much!

+2  A: 

There are many good ways to optimize Javascript.

This is not one of them.
The cost of searching up the scope is minute.

In addition, you're misunderstanding the this keyword.
The this keyword is an implicit parameter to every function, which will either be the global window object, the instance that the function was called on, or the first parameter passed to call or apply.
The this object will refer to a normal Javascript object; its properties have no scope.

SLaks
A: 

First, have you profiled your application and do you know that this code is a bottleneck?

There's no point optimizing this if your applications spends 99.9% of its time doing something else.

Ben S
Sorry, I don't know. I'm just writing the code and wanted to know the best practice so I don't have to go back and undo a bunch of stuff. I guess it's not really performance related, but best practice.I see some scripts even storing the this keyword as a local variable...I didn't know if there was a point to doing that.Thanks though.
Geromey