I've been reading through quite a bit regarding this topic but am
finding myself confused.
Here is the scenario:
I have a javascript class defined with methods whereas each has
references to "this." As everyone is aware of, when you attach and
event from an element to a class method and the class method
references "this", the scope of "this" refers not to the class but
rather to the element firing the event.
So, lets consider the following code:
function objclass {
this.parentDiv = document.getEle mentById("paren tdiv");
this.x = 0;
this.y = 0;
this.elementScr olled = elementScrolled ;
this.createElem ent= createElement;
}
function elementScrolled () {
this.x = this.parentDiv. scrollLeft;
this.y = this.parentDiv. scrollTop;
alert(this.x + "x" + this.y);
}
function createElement() {
var element = document.create Element("div");
element.id = "parentdiv" ;
element.onscrol l = this.elementScr olled();
this.parentDiv. appendChild(ele ment);
}
If I run this code, the references to this.x and this.y return
nothing... or "undefined. "
How do I solve this problem? I want to be able to access the "this"
reference within my event handler. Any quick fix suggestions?
Thank you!
finding myself confused.
Here is the scenario:
I have a javascript class defined with methods whereas each has
references to "this." As everyone is aware of, when you attach and
event from an element to a class method and the class method
references "this", the scope of "this" refers not to the class but
rather to the element firing the event.
So, lets consider the following code:
function objclass {
this.parentDiv = document.getEle mentById("paren tdiv");
this.x = 0;
this.y = 0;
this.elementScr olled = elementScrolled ;
this.createElem ent= createElement;
}
function elementScrolled () {
this.x = this.parentDiv. scrollLeft;
this.y = this.parentDiv. scrollTop;
alert(this.x + "x" + this.y);
}
function createElement() {
var element = document.create Element("div");
element.id = "parentdiv" ;
element.onscrol l = this.elementScr olled();
this.parentDiv. appendChild(ele ment);
}
If I run this code, the references to this.x and this.y return
nothing... or "undefined. "
How do I solve this problem? I want to be able to access the "this"
reference within my event handler. Any quick fix suggestions?
Thank you!
Comment