I created an object and it works great when I have one instance of the object. This isn’t the actual Object, but the concept is the same.
function foo(name){
this.name = name;
}
foo.prototype.CreateElement = function(){
var newElement = document.createElement("a");
that = this;
newElement.onclick = function(){
that.SayName(this);
};
document.getElementsByName("body")[0].appendChild(newElement);
}
foo.prototype.SayName = function(LinkObj){
alert(this.name);
LinkObj.href = "http://google.com";
}
I was told that by saving the instance of this to a variable (in this case that), I would still get a reference to the correct object instance for the SayName method. This would leave this to represent the instance of the element passed in from the onclick. This all seems to work properly with only one instance, but when I create multiple instances of the object I end up with the last instance being the instance supplied in the onclick event.
I initialize two objects like this
var ObjOne = new foo("Ted");
ObjOne.CreateElement();
var ObjTwo = new foo("Steve");
ObjTwo.CreateElement();
and when the onclick fires for ObjOne, I get the object instance for ObjTwo and so this.Name is set to Steve.
Does anyone know how I can get the right object instance when the onclick event fires from various instances? I assume i need to bind the correct instance with call, but i’m not really sure how to.
Thanks in advance and hope this wasn’t to confusing.
The problem is this line:
You declared
thatwithout usingvar, which means it is global, i.e., all your instances are updating the same globalthatvariable. Do this instead:Then
thatwill be local to each. (That is, local to each closure of the CreateElement function.)Demo: http://jsfiddle.net/SEsLJ/
Also,
document.getElementsByNameshould bedocument.getElementsByTagName(assuming you didn’t actually give the body a name attribute equal to “body”).