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 theonclick
event itself. It is not bound automatically to other functions.Pass it on like this:
and the html:
You function
click
doesn't know about 'this'. Change it to:and
Your question seems to be about the value of
this
. In an inline handler,this
will represent thewindow
. You can set the value ofthis
using.call()
, so it gives the value you desire.Example: http://jsfiddle.net/patrick_dw/5uJ54/
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:Your function is being called against no particular object, so the
window
is implied. By doing:...you end up with:
Giving the desired context. You can also pass the event object:
...so you end up with:
So now in your
click()
function, you'll have theevent
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