JavaScript What Is This And How Do I Use It
<< July | August | September >>
Tuesday, 10th August 2010
I was asked today to explain the "this" keyword in JavaScript, so here is a quick explanation of how it works...
Simple "this" example
<p onclick="alert(this.id);" 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 "this.id", you get the id of the paragraph, i.e. "example".
A Bit More Complicated "this" example
<p id="example">Click On Me</p>
<script type="text/javascript">
document.getElementById("example").onclick = function () {
alert(this.id);
};
</script>
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 the one that got clicked on - really handy!
You Are Here: Home » Blog » JavaScript What Is This And How Do I Use It