Hello, I'm trying to develop a series of classes to validate my webforms, I'll try to explain the idea: I what to create a HTML form whiteout any javascript event, for example: <form id="form1" name="form1" method="post" action=""> <input type="button" name="button" id="button" value="Button" /> </form> I call the class in the head section (or in external javascript file) For example: var alert=new alert_button('button'); The class alert_button would have a method called onclick For example: alert_button.onclick=function(){ alert('HELLO'); } What I would what to do is when I call var alert=new alert_button('button'); all the methods and properties from alert_button class woud be passed to the object of the element form whit the ID informed (in this case the id button that is from a input element)! This would be very useful because if I what to add a new methods to that elements I would only have to add the method to the class! The problem is that I cant do that passing of methods, I think that the problem is because the object is already instantiated after I try to pass the new methods! (Note that the object type in this case is a input type button, but it could be any type, for example it could be a anchor link). Here is a example of my code: <head> <title>Class Test</title> <script type="text/javascript"> function elemento(id){ this.id=id; } elemento.prototype.onclick=function() { return 0; } function botao(id,men){ elemento.call(this,id); var targ=document.getElementById(id); this.men=men; targ.call(targ,this); } botao.prototype=new elemento(); botao.prototype.onclick=function() { alert(this.men); } function loade() { var teste=new botao('button',"HELLO"); var teste=new botao('button2',"HELLO TOO"); } </script> </head> <body onload="loade()"> <form id="form1" name="form1" method="post" action=""> <input type="button" name="button" id="button" value="Button" /> <input type="button" name="button" id="button2" value="Button" /> </form> </body> </html> Code (markup): Can any one help me make this work? Thanks for the help!
Hello, try this code: function elemento(id){ this.id=id; } elemento.prototype.onclick=function() { return 0; } function botao(id,men){ elemento.call(this,id); var targ=document.getElementById(id); this.onclick = function() { alert(men); } this.men=men; for (value in this) { if (typeof(this[value]) == 'function') { targ[value] = this[value]; } } } botao.prototype=new elemento(); function loade() { var teste=new botao('button',"HELLO"); var teste=new botao('button2',"HELLO TOO"); } Code (markup): There are some reasons for your code not to work. It has to do with how variables scope work in javascript. Also, call and apply are a bit outdated. Cheers