need more understanding of how to use the word "this"

L

lawrence

I'm trying to gain a better understanding of javascript by studying
examples. I noticed this in an online tutorial. I don't get the use of
"this".
You might want to add some event handler for an event to an element to
which there is already an event handler attached. That is possible by
storing the old event handler somewhere and then writing a new
function
which calls the old event handler.
For example suppose you have a document with buttons with onclick
handlers
<INPUT TYPE="button" NAME="aButton" VALUE="praise God"
ONCLICK="alert('Hail the Kibo');"and you want add script that disables the event handler temporarily
then
you store the old event handler
var button = document.formName.aButton;
button.oldOnClick = button.onclick;
and write your new click handler which calls the oldOnClick when
necessary
function disabledButton (evt) {
if (this.disabled)
return false;
else
if (this.oldOnClick)
this.oldOnClick(evt);
}
button.onclick = disabledButton;
Now you can set
button.disabled = false;
to disable the button and
button.disabled = true;
to enable it. Complete example:

In the these two lines:

function disabledButton (evt) {
if (this.disabled)

Where did the "this" come from and what does it refer to? Also, where
did the property "disabled" come from???
 
M

Michael Winter

[snip]
In the these two lines:

function disabledButton (evt) {
if (this.disabled)

Where did the "this" come from and what does it refer to?

This keyword, this, is an operator. It always references an object, though
which object depends upon context. In this case, it refers to the button.

When

button.onclick = disabledButton;

is executed, the onclick property of the object, button, refers to the
function, disabledButton. It becomes a method of that object. When you
click the button, disabledButton is called and because it is a member of
button, the this operator refers to that object.
Also, where did the property "disabled" come from???

Hopefully, it's now obvious: it is the disabled property of the button.

Does that help?

Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top