Thursday, February 14, 2008

Javascript, Scope Context ohh my

Ok,

So my last post started to dive into the scope, and context around javascript exection. I have since come accross a really good post by Mike West. This article showed another solution to the issue of loosing scope.

I ran into a problem where I had a javascript object and I wanted a functon in the object to be called. I am a big fan of composing my methods into smaller methods, so like many functions I write this function made calls to other functions that were within in the same object. So for example we had something like:
function world(){    
 this.spin=function(degrees){        
  //do something    
 }    
 this.handleClick=function(){        
  this.spin(90);    
 }
}



When I attached the handleClick function to the event handler of a button for example. I would loose the ability to call the rotate method. This was due to the context "this" (See the article I referenced above for a good explanation).

The soltion Mike West highlighted (which appears was borrowed out of prototype Javascript which is referenced in his article). Is to extend the function object itself. We can define a bind function which allows us to change the call context prior to calling our method.

Function.prototype.bind = function(obj) { 
 var method = this, temp = function() { 
  return method.apply(obj, arguments); 
  }; 
 return temp; 
} 


Using this solution is extremly easy. You can simply say object.event=myWorld.handleClick.bind(myWorld);

No comments: