[JavaScript] Change Scope (Context) of Anonymous Function


This post is an extension of previous post "[JavaScript] Scope (Context) of Event Handler Function [2]". In this post, we will discuss how to change the scope (context) of a JavaScript anonymous function. The anonymous function in JavaScript has wide uses, for example, as an event handler function. See the following code snippet:

element.onclick = function() {
  console.log(this);
};

We use an anonymous function as the onclick event handler of HTML DOM element. If you register the event handler as above, this keyword in the anonymous event handler function refers to the DOM element itself. What if we want to change the scope (context) of the anonymous event handler function to global scope (i.e., window) or other scope?

The answer is Function.prototype.bind() introduced in recent browsers. For example:

element.onclick = function() {
  console.log(this);
}.bind(window);

The above code changes the scope (context) of the anonymous function to global scope. Another example:

element.onclick = function() {
  console.log(this);
}.bind(this);

Will bind the scope of the anonymous function to the scope when onclick event of the element is registered.

The Function.prototype.bind() is great, but for older browsers (for example, IE8) which do not support Function.prototype.bind(), we need to implement custom Function.prototype.bind() in JavaScript code. For more details of Function.prototype.bind(), please refer to reference [1].


References:

[1]Function.prototype.bind() - JavaScript | MDN
[2][JavaScript] Scope (Context) of Event Handler Function