The answer from @ibrahimmahrir does the job, but I wanted to consolidate a few points.
As many JavaScript developers struggle to understand, the this
keyword is a moving target. In traditional OOP languages, an object method is exclusive to the object, so this
is defined as the object to which it is attached.
JavaScript functions are more promiscuous, and can be attached to multiple objects. In JavaScript, this
refers to the object which is currently invoking the function, not necessarily the one to which it was originally attached.
For an Event Handler function, the invoking object is the element to which it is attached, not the original object; thus this
refers to the element. The usual safe method is to store a reference to the original object in a different variable, often called that
:
oClass = new CClass();
function CClass() {
var that = this; // a reference to the original object
this.m_s = "hello :-/";
this.OnEvent = OnEvent;
var r = document.getElementById("test");
r.addEventListener('click', this.OnEvent);
function OnEvent() {
alert(that); // this is now the object
alert(that.m_s); // this works
}
}
The comments above are my updated comments. I have also removed the with
statement which wasn’t contributing much and which is seriously discouraged.
Oh, and I have changed the event to click
to make it easier to test.
While we’re on the confusion with this
, it is not necessarily the element which started things off. Suppose we now include a span
:
<div id="test">click <span>over</span> here</div>
Clicking on the span
will trigger the event listener, even though the you didn’t actually click on the div
to which it is attached. In this case the event is bubbled from the span to the div.
Here this
refers only to the div
element with the event listener. If you want to reference the span
, you will need event.target
:
function OnEvent(event) { // include event parameter
alert(this); // the element attached
alert(event.target); // the element clicked
alert(that); // this is now the object
alert(that.m_s); // this works
}
Here is an updated fiddle: https://jsfiddle.net/osk083xv/
with
statement is strongly discouraged, and is disallowed in Strict mode. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Wylen