Let’s first take a look at JavaScript code =>
function ConstructNodes(className,hiddenId,alertMsg,formName){
this.className = className;
this.hiddenId = hiddenId;
this.alertMsg = alertMsg;
this.formName = formName;
}
ConstructNodes.prototype.getId = function(){
var nodes = document.getElementsByClassName(this.className);
for (var i=0;i<nodes.length;i++){
nodes[i].onclick = function(){
var r = confirm(this.alertMsg);
if (r==true){
alert(this.hiddenId); // undefined
} else {
return;
}
};
}
};
var obj = new ConstructNodes("className","hiddenId","Are you sure ?","formName");
obj.getId();
My problem in this situation is that defined objects are undefined under getId’s anonymous function , how can I solve this situation ? thanks
Your code is incorrectly assuming that
thiswill refer to a “ConstructNodes” object inside the event handlers. It won’t; it’ll be the element. Instead, storethisin an object, and things will be better:(It’s not at all clear what you’re trying to do, so there may be some issues still.)