The 'this' keyword

The this keyword

See sections 5H and 7F of the book.

This page has been translated intoFrench,Russian,and Chinese.

One of the most powerful JavaScript keywords is this. Unfortunatelyit is hard to use if you don't exactly know how it works.

Below I explain how to use it inevent handling.Later on I'll add some information about other uses of this.

Owner

The question that we'll discuss for the remainder of the pageis: What does this refer to in the function doSomething()?

function doSomething() {
   this.style.color = '#cc0000';
}

In JavaScript this always refers to the “owner” of the functionwe're executing, or rather, to the object that a function is a method of.When we define our faithful function doSomething() in a page, its owneris the page, or rather, the window object (or global object) of JavaScript. An onclickproperty, though, is owned by the HTML element it belongs to.

This "ownership" is the result of JavaScript's object oriented approach. See theObjects as associative arrays page for some moreinformation.

------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          --------------------                          |
|          | onclick property |                          |
|          --------------------                          |
|                                                        |
----------------------------------------------------------

If we execute doSomething() without any more preparation the thiskeyword refers to the window and the function tries to change the style.color of the window. Since thewindow doesn't have a style object the function fails miserably and produces JavaScript errors.

Copying

So if we want to use this to its full extent we have to take care that the function that uses itis "owned" by the correct HTML element. In other words, we have tocopy the function to our onclick property.Traditional event registration takes care of it.

element.onclick = doSomething;

The function is copied in its entirety to the onclick property (which now becomesa method). So if the event handler is executed this refers to the HTML element and itscolor is changed.

------------ window --------------------------------------
|                                                        |
|                                                        |
|                                                        |
|   ----------------                                     |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          -----------------------          |            |
|          |copy of doSomething()|  <-- copy function    |
|          -----------------------                       |
|                                                        |
----------------------------------------------------------

The trick is of course that we can copy the function to several event handlers. Each time thiswill refer to the correct HTML element:

------------ window --------------------------------------
|                                                        |
|                                                        |
|                                                        |
|   ----------------                                     |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          -----------------------          |            |
|          |copy of doSomething()|  <-- copy function    |
|          -----------------------          |            |
|                                           |            |
|   -----------------------                 |            |
|   | another HTML element| <-- this        |            |
|   -----------------------     |           |            |
|               |               |           |            |
|          -----------------------          |            |
|          |copy of doSomething()|  <-- copy function    |
|          -----------------------                       |
|                                                        |
----------------------------------------------------------

Thus you use this to the fullest extent. Each time the function is called,this refers to the HTML element that is currently handling the event, the HTMLelement that "owns" the copy of doSomething().

Referring

However, if you useinline event registration

<element οnclick="doSomething()">

you do not copy the function! Instead, you refer to it, and the difference is crucial.The onclick property does not contain the actual function, butmerely a function call:

doSomething();

So it says “Go to doSomething() and execute it.” Whenwe arrive at doSomething() the this keyword once again refers to the globalwindow object and the function returns error messages.

------------ window --------------------------------------
|                                          / \           |
|                                           |            |
|                                          this          |
|   ----------------                        |            |
|   | HTML element | <-- this         -----------------  |
|   ----------------      |           | doSomething() |  |
|               |         |           -----------------  |
|          -----------------------         / \           |
|          | go to doSomething() |          |            |
|          | and execute it      | ---- reference to     |
|          -----------------------       function        |
|                                                        |
----------------------------------------------------------

The difference

If you want to use this for accessing the HTML element that is handling the event,you must make sure that the this keyword is actually written into the onclick property.Only in that case does it refer to the HTML element the event handler is registeredto. So if you do

element.onclick = doSomething;
alert(element.onclick)

you get

function doSomething()
{
	this.style.color = '#cc0000';
}

As you can see, the this keyword is present in the onclick method.Therefore it refers to the HTML element.

But if you do

<element οnclick="doSomething()">
alert(element.onclick)

you get

function onclick()
{
	doSomething()
}

This is merely a reference to function doSomething(). The thiskeyword is not present in the onclick method so it doesn't refer to the HTML element.

Examples - copying

this is written into the onclick method in the following cases:

element.onclick = doSomething
element.addEventListener('click',doSomething,false)
element.onclick = function () {this.style.color = '#cc0000';}
<element οnclick="this.style.color = '#cc0000';">
Examples - referring

In the following cases this refers to the window:

element.onclick = function () {doSomething()}
element.attachEvent('onclick',doSomething)
<element οnclick="doSomething()">

Note the presence of attachEvent(). The main drawback of theMicrosoft event registration modelis that attachEvent() creates a reference to the function anddoes not copy it. Therefore it is sometimes impossible to know which HTML currently handlesthe event.

Combination

When using inline event registration you can also send this to the functionso that you can still use it:

<element οnclick="doSomething(this)">

function doSomething(obj) {
	// this is present in the event handler and is sent to the function
	// obj now refers to the HTML element, so we can do
	obj.style.color = '#cc0000';
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值