Steve Fenton

JavaScript What is “this” and How Do I Use It

I was asked today to explain the “this” keyword in JavaScript, so here is a quick explanation of how it works…

Simply this Example

<p onclick="alert(;" id="example">Click On Me</p>

this is a great way of getting the HTML element that started off an event. In the little snippet above, this is the paragraph. When you call, you get the id of the paragraph, i.e. “example”.

Slightly More Complicated this Example

<p id="example">Click On Me</p>
    document.getElementById('example').onclick = function () {

This example works in exactly the same way as before, so you don’t have to put your events on the HTML element to use this. In this example we bind the event using JavaScript and everything directly inside of our function will magically understand that this refers to the paragraph you click on.

If you bind the same event handler to lots of HTML elements, this will always be whichever one got clicked on – really handy!

Written by Steve Fenton on