Sunday, August 05, 2007

Javascript keyword "this" explain

In JavaScript this always refers to the “owner” of the function we'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 owner is the page,
or rather, the window object (or global object) of JavaScript.
An onclick property, though, is owned by the HTML element it belongs to.

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 onclick="this.style.color = '#cc0000';">

Examples - referring
In the following cases this refers to the window:
element.onclick = function () {doSomething()}
element.attachEvent('onclick',doSomething)
<element onclick="doSomething()">
<a href="#" id="a1" style="color: #ddd"> test </a>
<script type="text/javascript" charset="utf-8">
function doSomething() {
this.style.color = '#cc0000';
}

var a1 = $('a1');
// a1.addEventListener('click', doSomething, false);
a1.onclick = doSomething; // copy function.
</script>

No comments :