I can't access a JavaScript variable from another function that has been instantiated in the constructor function. It returns undefined
.
I am instantiating a new object of the class Box
, and in the constructor function, defining instance variables, creating HTML elements and setting up an event listener. The handler for this listener, clickHandler
, is a function that is defined on the prototype. From clickHandler
, I am trying to access the this.selected
variable. But I get undefined
.
The code:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="element1"></div>
<br/>
<div id="element2"></div>
<script type="text/javascript" src="script.js"></script>
<script>
init([{id: "element1"}, {id: "element2"}]); //call init function
</script>
</body>
</html>
Javascript script.js
function Box(id, count) { //the class
this.selected = false; //need this variable in clickHandler
this.div = document.createElement("div");
this.div.id = "container" + count;
this.div.style.width = "250px";
this.div.style.height = "150px";
this.div.style.border = "1px solid black";
document.getElementById(id).appendChild(this.div);
this.div.addEventListener("click", this.clickHandler, false); //add event listener on the created div element
}
Box.prototype.clickHandler = function() { //click handler
console.log("clickHandler, selected = " + this.selected); // undefined
};
function init(settings) {
//var obj;
for(var i = 0; i < settings.length; i++) {
new Box(settings[i].id, (i+1)); //instantiate new object
}
}
How can I access the this.selected
variable in various event handler functions? I plan to listen for multiple events and need the this.selected
variable for that. Thank you for the help.