I understand how this
works when invoked on an object, but I'm having trouble understanding how this
works when called from a "static" context.
Given the following HTML:
<body onload="myOnLoad()">
<div id="someDiv">0</div>
</body>
...and this javascript:
function myOnLoad() {
var inc = new Incrementer();
/*** increase() works fine here, "this" refers to "inc" ***/
inc.increase();
inc.setOnClick();
}
function Incrementer() {
this.value = 0;
}
Incrementer.prototype.setOnClick = function() {
/*** increase fails to update someDiv when clicked.
"this" is not "inc" ***/
document.getElementById("someDiv").onclick = this.increase;
}
Incrementer.prototype.increase = function() {
document.getElementById("someDiv").innerHTML = ++this.value;
}
...clicking on someDiv
turns it's innerHTML into NaN
. I realize that this is because the onclick event is unaware of the existence of inc
, but what I don't understand is how to pass 'inc' into the onclick event.
Do you know how I can access inc
's variables from the context of an onclick? Or, is there a more conventional way of doing this?
I'm mostly interested in learning how I can make someDiv
's onclick refer to that specific instance, inc
.