Saving this for use in nested functions objects

suggest change

One common pitfall is to try and use this in a nested function or an object, where the context has been lost.

document.getElementById('myAJAXButton').onclick = function(){
    makeAJAXRequest(function(result){
      if (result) { // success
        this.className = 'success';
      }
    })
}

Here the context (this) is lost in the inner callback function. To correct this, you can save the value of this in a variable:

document.getElementById('myAJAXButton').onclick = function(){
    var self = this;
    makeAJAXRequest(function(result){
      if (result) { // success
        self.className = 'success';
      }
    })
}

ES6 introduced arrow functions which include lexical this binding. The above example could be written like this:

document.getElementById('myAJAXButton').onclick = function(){
    makeAJAXRequest(result => {
      if (result) { // success
        this.className = 'success';
      }
    })
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Context this:
* Saving this for use in nested functions objects

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
98 Context this
102 Tilde