Reputation: 5500
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
Upvotes: 2
Views: 529
Reputation: 3422
It's undefined
because you can not access this
in that function just like that.
Any function is called with it's own execution context, thus the this
in that case is something different than outside of the function.
You can solve that by defining a var
in the outer scope and access it in the inner, like this:
function ConstructNodes(className,hiddenId,alertMsg,formName){
this.className = className;
this.hiddenId = hiddenId;
this.alertMsg = alertMsg;
this.formName = formName;
}
ConstructNodes.prototype.getId = function() {
var _this = this; // a reference that will be known in your closure/function
var nodes = document.getElementsByClassName(this.className);
for (var i = 0; i < nodes.length; i++) {
nodes[i].onclick = function(){
if (confirm(_this.alertMsg)) {
alert(_this.hiddenId); // no longer undefined
} else {
return;
}
};
}
};
var obj = new ConstructNodes("className", "hiddenId", "Are you sure?", "formName")
obj.getId();
Upvotes: 1
Reputation: 28598
It took me a minute to understand your question.
You cannot refer to this
in an anonymous function in getId.
you must save this
into a variable for example var me = this
outside the anonymous function, and then use me.hiddenId
.
Here is a JSFiddle to demonstrate that.
Upvotes: 1
Reputation: 413702
Your code is incorrectly assuming that this
will refer to a "ConstructNodes" object inside the event handlers. It won't; it'll be the element. Instead, store this
in an object, and things will be better:
ConstructNodes.prototype.getId = function(){
var nodes = document.getElementsByClassName(this.className), obj = this;
for (var i=0;i<nodes.length;i++){
nodes[i].onclick = function(){
var r = confirm(obj.alertMsg);
if (r==true){
alert(obj.hiddenId); // undefined
document.getElementById(obj.hiddenId).value = this.id;
alert(obj.hiddenId);
} else {
return;
}
};
}
};
(It's not at all clear what you're trying to do, so there may be some issues still.)
Upvotes: 4