I can’t seem to return an object from a function, the console.log inside the function prints out the property values fine but once outside the function I’m getting “Uncaught ReferenceError: firstOn is not defined”
Any help would be appreciated, thanks!
myElement = document.getElementById("testButton");
function Server(name,tables,startTime) {
this.name = name;
this.tables = tables;
this.startTime = startTime;
}
document.forms.server1.button.onclick = function() {
var name = document.forms.server1.servername.value;
var tables = document.forms.server1.servertables.value;
var startTime = document.forms.server1.servertime.value;
var firstOn = new Server(name,tables,startTime);
document.forms.server1.button.innerHTML = "Saved!";
console.log(firstOn.name);
console.log(firstOn.tables);
console.log(firstOn.startTime);
return firstOn;
};
myElement.onclick = function() {
console.log(firstOn.name);
console.log(firstOn.tables);
console.log(firstOn.startTime);
};
firstOnis an object that was created and returned from thedocument.forms.server1.button.onclickevent handler. The return value from that event handler went into the system (that’s where event handlers return to) and was never stored anywhere so it was cleaned up by the system with garbage collection.Meanwhile, your
myElement.onclickevent handler does NOT have access to thefirstOnobject because it wasn’t saved anywhere thatmyElement.onclickcan reach.If you want
firstOnto be usable after thedocument.forms.server1.button.onclickevent handler, you have to save it somewhere that the second click handler can each. That could be in a global variable or it could be a property of some other object that is globally accessible. As your code is written right now, thefirstOnobject is created, but never stored anywhere so it is happily cleaned up by the garbage collector and is not reachable by other code.