0

This is a bit of a strange one. I have been trying to call a function in a child object from the parent object but it seems to be going out of scope in onbeforeunload function. These function calls work outside of a onbeforeunload, so it only fails when called in onbeforeunload. I can fix it by making the child object a global but I was trying to avoid that. Anyone know why my childobject is out of scope when called in onbeforeunload? Notice I call that same function in windows onload event and it works fine. Here is the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>

<head>
<title>Broken HTA</title>    
<HTA:APPLICATION 
 ID="Broken HTA"
 APPLICATIONNAME="Broken HTA"
 BORDERSTYLE = "flat"
 CAPTION="Yes"
 CONTEXTMENU = "no"
 INNERBORDER = "no"
 MAXIMIZEBUTTON = "no"
 MINIMIZEBUTTON = "yes"
 NAVIGABLE = "No"
 SCROLL = "auto"
 SCROLL FLAT = "Yes"
 SELECTION="no"
 SYSMENU="yes"
 SHOWINTASKBAR="yes"
 SINGLEINSTANCE="yes"
 VERSION = "1.0"
 BORDER="thick"
 >



<script language="javascript" type="text/javascript">

var myparent;

function windowLaunch()
{
    myparent = new parent();
    myparent.getchildvalue();
    window.onbeforeunload = myparent.getchildvalue;
    window.resizeTo(500, 610);
}

function parent()
{
    this.mychild = new childobject("myinput");
    this.getchildvalue = function()
    {
        var tmpval = this.mychild.returnvalue();
    };

}

function childobject(thename)
{
    this.myprop = thename;
    this.returnvalue = function()
    {
        return (document.getElementById(this.myprop).value);
    };
}

</script>
</head>

<body id="thebody" onload="windowLaunch();">
<div id="outerdiv">
        <span title="This Input Box">My Input:</span><br />
        <input id="myinput" style="width: 290px"/>
</div>
</body>

</html>

1 Answers1

1

this is based on how a function is called. Calling myparent.getchildvalue() is fine, but as soon as you assign myparent.getchildvalue as a handler, it will be called out of context. You can demonstrate this simply:

var obj = { val: 42, fn: function(){ alert(this.val) } };
    ref = obj.fn;

alert(obj.fn === ref); // true, so expect the following to do the same thing...

obj.fn(); // 42, so far so good
ref(); // undefined. uh oh...

You can get around this by wrapping:

...
window.onbeforeunload = function(){ myparent.getchildvalue(); };
...

or binding:

...
window.onbeforeunload = myparent.getchildvalue.bind(myparent);
...
davin
  • 44,863
  • 9
  • 78
  • 78
  • Similar to http://stackoverflow.com/questions/8656774/why-this-is-not-point-to-js-global-scope-in-the-code-example/8656817#8656817 – davin Jan 13 '12 at 23:15