I am trying to understand how the this
keyword works in JavaScript and I made this script:
function click(){
this.innerHTML="changed";
}
Used in this HTML:
<button id="clicker" onclick="click()" >Click me</button>
But it doesn't work, can anyone explain why?
this
exists only in the scope of the onclick
event itself. It is not bound automatically to other functions.
Pass it on like this:
function click(element){
element.innerHTML="changed";
}
and the html:
<button id="clicker" onclick="click(this)" >Click me</button>
You function click
doesn't know about 'this'. Change it to:
function click(elemenet){
element.innerHTML="changed";
}
and
<button id="clicker" onclick="click(this)" >Click me</button>
Your question seems to be about the value of this
. In an inline handler, this
will represent the window
. You can set the value of this
using .call()
, so it gives the value you desire.
Example: http://jsfiddle.net/patrick_dw/5uJ54/
<button id="clicker" onclick="click.call(this)" >Click me</button>
Now in your click
method, this
will be the <button>
element.
The reason is that your inline attribute gets wrapped in a function, which itself has the context of the element. But it doesn't actually call your function from that context. By doing click()
, it ends up looking like:
function onclick(event) {
click();
}
Your function is being called against no particular object, so the window
is implied. By doing:
<button id="clicker" onclick="click.call( this )" >Click me</button>
...you end up with:
function onclick(event) {
click.call( this );
}
Giving the desired context. You can also pass the event object:
<button id="clicker" onclick="click.call( this, event )" >Click me</button>
...so you end up with:
function onclick(event) {
click.call( this, event );
}
So now in your click()
function, you'll have the event
as you'd expect.
Also, you may have issues with using click
as a function name. I'd change it.
Have a look at http://www.quirksmode.org/js/this.html