I am currently learning OOP Javascript but struggling with understanding the this
keyword and working with events.
My goal is to bind a common event to multiple DOM objects while storing data about these objects in a global container for better performance.
Here is a simplified version of what I am trying to do:
function ClassThatDoesSomething() {
/* holds node ids for processing in this.init */
this.nodes = new Array();
/* stores processed node data for quick access */
this.nodeData = new Array();
this.addNodes = function(/* ids */) {
/* appends node ids to local variable (this.nodeData) */
}
function init() {
/* gathers data from all nodes that were
added before and stores it in this.nodeData */
/* the issue here is that 'this' refers to the window element*/
addEvent(window,'scroll',this.scroll);
}
function scroll() {
/* perform actions when user scrolls the page */
/* 'this' also references the window element here */
}
addEvent(window,'load',this.init);
}
Later, in the document body, I could simply do this:
var Ctds = new ClassThatDoesSomething();
And then, add DOM elements like this:
Ctds.addNodes(ids);
No additional implementation code would be needed.
QUESTION: How can I access the instance of the JS class in the init
and scroll
methods instead of the window element.
It doesn't necessarily have to be done through the this
keyword, but I haven't been able to find an alternative solution yet.
P.S.
addEvent
is a basic function for attaching events, ensuring compatibility with IE and Firefox.- The code I currently have works fine in a procedural manner, but I am looking to refactor it using OOP principles.
- As a side note, I've heard conflicting opinions about using getter/setter methods in JavaScript, is it acceptable to use them?