This is a follow up question from my last question.
Simple javascript prototype issue
I am a bit new using JavaScript prototype so sorry for the second post.
I want to assign the clicked element id to the this.name array.
task.prototype.init=function(){
this.name=[]; //this.name array has to be defined here
for (var i; i<5; i++){
var Link=document.createElement('a');
Link.innerHTML='click';
Link.id=value[i]; //I want to assign the value to the this.name array
Link.href='#'
Link.onclick=this.changeName;
document.body.appendChild(Link);
}
}
task.prototype.changeName=function(){
//How do I push the this.id to the property this.name?
//the code below won't work because this refer to the <a> element.
this.name.push(this.id);
return false;
}
Any tips for the task?
Your prototype is okay, the problem is that
thison event handlers is always the element that caused the event to be triggered. In JavaScript, the value ofthisinside a function depends on how the function is called.If you want
thisto be bound to a certain value, you can create a bound function withFunction.prototype.bind:Note however that
bindis IE9+ only. A workaround would be:(Style note: I’d use
linkinstead ofLink; the convention in js is to leave uppercase initials to constructors).