HTA Javascript-为什么对象在onbeforeunload中超出范围



这有点奇怪。我一直试图从父对象调用子对象中的函数,但它似乎超出了onbeforenload函数的范围。这些函数调用在onbeforeunload之外工作,因此只有在onbeforunload中调用时才会失败。我可以通过将子对象设置为全局对象来解决这个问题,但我试图避免这种情况。有人知道为什么我的子对象在onbeforeunload中调用时超出范围吗?请注意,我在windows onload事件中调用了相同的函数,它运行良好。这是代码:

<!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>

this基于函数的调用方式。调用myparent.getchildvalue()是可以的,但一旦将myparent.getchildvalue指定为处理程序,就会在上下文之外调用。你可以简单地证明这一点:

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...

你可以通过包装来解决这个问题:

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

或绑定:

...
window.onbeforeunload = myparent.getchildvalue.bind(myparent);
...

相关内容

  • 没有找到相关文章

最新更新