Question:
What is "this"?
Answer:
This is a reserved word used by almost all programming languages. It basically contains all information
about the current object.
Question:
What are some examples of "this"?
Answer:
If a button issues an onclilck event, then this would be that button.
"this" would contain ALL information about that button. Consider the below html...
<button id="myButton" class="btnClass" value="clickMe">Click me<button>
this === Object HTMLButtonElement
this.id === "myButton"
this.className === "btnClass"
this.value === "clickMe"
this.innerHTML === "Click me"
Question:
How does the onclick event know who "this" is?
Answer:
"this" knows, because the onclick event is attached to that button. e.g.:
docment.getElementById("myButton").onclick = myClick;
Therefore, when myClick() runs, it knows this is an HTML button element, and this.id is "myButton".
Question:
What is the benefit of "this"?
Answer:
If you have the same onclick event handler, e.g. myClick(), attached to several buttons,
this automatically knows which button "this" is. So you do not have to write
extra code to find out what button is the current object.
For example,
if several buttons run AJAX to get data from the server, and each button's value
is the name of the file on the server with the data you want, simply send this.value
to your AJAX module, instead of having to write a lot of code to determine what
file on the server you want!