Monday, November 14, 2011

function invocation pattern

In Javascript, there are a few ways to invoke a function, and depending on the context, a function can be a function, or a method.

The Function Invocation Pattern is the most dangerous one of all, simply because it is so easy to get lost in the "this" madness, where a developer would expect "this" to refer to this function, when in fact it's referring to the "global object". Let's see a quick example.



If "this" is referenced in the function "add", "this" would refer to the "global object".

But a function is an object, right. And if function "add" was an inner function to another function "calculate", the right expectation would for "this" inside "add" to refer to the outer function object "calculate".



The workaround is to create a new variable, "that", and bind it to "this" inside of "cacl", but outside of "add", and refer to "that" inside "add" to access "mathObject" object.

Hope that helps you understand how to avoid this bug.