Clip Art This
Pierce Home
Computer Science 555 Website Development using JavaScript and AJAX - 3 Units
Section:
3179
Instructor:
Brad Gilbert
Pierce Mailbox:
612
Email:
pierce@wavethunder.com
Wednesday Office Hours:
5:00 -   5:40 PM COSC 1507
Wednesday Lab:
5:45 -   7:50 PM COSC 1507
Wednesday Lecture:
7:55 - 10:00 PM MATH 1511
Other classes:
CS-575
this
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!

Brad Gilbert · Fall 2011
Computer Science · Pierce College · Woodland Hills CA · 818-719-6401