Sunday, June 4, 2017

JavaScript this

JavaScript's this keyword can generate some intense debate among programmers.  This allows access to a function's execution context without having to specify that context in advance (or even know what the context is).  A thorough approach to understanding how the value of this is determined is to completely consume the ECMAScript Language specification for an edition of your choice, such as edition 5.1 (https://ecma-international.org/ecma-262/5.1/).  Notably, if your function is defined as a member of an object (as a method), the value of this will be that object.  However, many JavaScript programmers prefer to take steps to ensure they are directly specifying a function's exectuion context.

A simple way for a programmer to ensure that she always refers to a consistent execution context when she needs to is to assign a value of this to a variable.  This is a reserved word and cannot be explicitly set with the assignment operator, but once a particular value of this is set to a variable the programmer can essentially replace an understanding of how this is determined with his understanding of variables.  Henceforth the programmer simply refers to the variable anywhere he would want to use the this keyword.  By convention many programmers choose to assign execution context to variables named that or self.

JavaScript also provides a trio of methods that allow you to supply an object that will serve as the execution context of a function.  Calling the bind method on a function returns a new function that uses the first argument that was passed to bind as the value of this.  Additional arguments passed to bind are passed on to the new function.  If your function funky requires parameters (a, b, c), pass these values to the new function via bind as follows: funky.bind(thisValue, a, b, c).

The call method, when called on a function, also accepts a value for this followed by a comma-delimited list of arguments for the original function.  Use funky.call(thisValue, a, b, c) to effectively execute funky(a, b, c) with thisValue as the value of this.

If you prefer to pass arguments to your function as an array, you can use the apply method as follows: funky.apply(thisValue, [a, b, c]).