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';
}
})
}