How to Access "this" in Event Handlers and Callbacks with globalThis Property

Use-Cases of this Tutorial

  • Know how access the global object "this" inside event handlers, AJAX callbacks, classes etc.
  • Know about the globalThis property.

One of the common things occurring in Javascript development is the need the access the global this object inside event handlers, AJAX callbacks etc. Historically we have been saving the value of this in a variable and then using that variable to access the global object.

// save value of this
var that = this;

$("#some-button").on('click', function() {
	// this refers to the current DOM element
	
	// access global function using the saved variable
	that.someFunction();
});
// save value of this
var that = this;

$.ajax({
    type: 'POST',
    url: '/some-url.php',
    data: { id: 655, name: 'New Name' },
    success: function(response) {
    	that.someFunction();
    }
});

globalThis

The globalThis is a global property referring to the global this value. This makes it very easy to access this inside callbacks, event handlers, inner function — basically anywhere where the global this gets overridden.

$("#some-button").on('click', function() {
	// access a global function
	globalThis.someFunction();
});
$.ajax({
    type: 'POST',
    url: '/some-url.php',
    data: { id: 655, name: 'New Name' },
    success: function(response) {
    	globalThis.someFunction();
    }
});