Tuesday 19 June 2018

javascript - Accessing instance variables from other functions

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







Test
















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.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...