Can somebody help me?
The following code works, but unfortunately a function call to doSomething() is necessary:
<body onload=init()>
</body>
<script>
function Startscreen()
{
this.doSomething(); //why is this call necessary and how else to solve it?
this.startscreenhtml =
" <form onsubmit=doSomething()> " +
" <input type=text /> " +
" </form> ";
document.write(this.startscreenhtml);
}
Startscreen.prototype.doSomething = function()
{
alert(123)
}
</script>
<script>
function init()
{
var startscreen = new Startscreen();
}
</script>
I do want to keep function doSomething as a function of object Startscreen.
edit: i do want to keep using document.write
Preferrably i want to declare doSomething outside of the constructor as i am doing now, because i believe that otherwise if i would call new Startscreen multiple times, the same function is created multiple times.
However, i tried many things to make this work without the call to doSomething, including declaring the function inside the constructor, but nothing worked.
My guess is that the call is necessary to make the function known, because if the code is read top to down, im assigning it to ‘onsubmit’ before i declared it.
Does anybody know how to solve this?
I don’t think that the code works as you think in the current form. The
doSomethingfunction will be called when you create the form, but it will not be called when you submit the form.To call the function from the
onsubmitevent, it has to be known in the global context, as the event handler is not called in the context of theStartscreeninstance. With your current code it’s not possible to call the function for two reasons; it’s not possible to reach from the global context, and as there is no reference left to the object instance there isn’t even an instance left that you can use to call it.(You could get the function from the prototype, or create a new instance of the object, but then your setup with an object would be completely pointless.)
If you want to keep the instance, you have to put it in a variable that survives the
initfunction:Now the object will still be around when the
onsubmitevent handler is called, so you can reach the function via the variable:This is of course not ideal, as you couple the object to the variable, but I hope that you gained some knowledge about what’s happening, so that you can come forward.
To use the method in the submit event without having a global variable to find it, you have to create an element so that you can hook up an actual function as the event handler. That way you can reach the method from the event handler:
This means that you can’t use
document.writeto create the form (or you need to give each form a unique id so that you can get a reference to the created element and hook up the event afterwards).