I’ve never really used JavaScript, but I know roughly what it’s about. Now I’m looking through some examples of chrome extensions, and I see this “pattern” quite a lot.
var Main = {
enable: function(){ window.addEventListener('mousemove', onMouseMove, false); },
onMouseMove: function(event){ _onMouseMove(event) },
_onMouseMove: function(event){
...lenghty implementation...
}
}
My question is, why? Is this some kind of optimization?
You’re question is a little vague; but I am guessing you’re asking why the developer has two
onMouseMovemethods instead of just doing all the work in one, ie:The answer is because of how scope is handled in JavaScript. In a nutshell, the
thiskeywork in most classical OOP languages (like Java) always refers to the parent class (Main) in the scope of a Function – JavaScript doesn’t work like this.As there are no classical classes in JavaScript, the
thiskeyword actually refers to the function which invoked it; that’s why thenewkeyword makes such a difference when creating a new object via its constructor function; for example:By delegating from
onMouseMoveto_onMouseMovethe scope remains bound to theMainobject instead of being bound to the object which triggered the mouse event. Another, more readable way of achieving this is to use a delegate, or if you’re using ES5, Function.bind