【问题标题】:HTA Javascript - why is object out of scope in onbeforeunload?HTA Javascript - 为什么 onbeforeunload 中的对象超出范围?
【发布时间】:2012-01-13 22:33:27
【问题描述】:

这有点奇怪。我一直在尝试从父对象调用子对象中的函数,但它似乎超出了 onbeforeunload 函数的范围。这些函数调用在 onbeforeunload 之外工作,因此只有在 onbeforeunload 中调用时才会失败。我可以通过使子对象成为全局对象来解决它,但我试图避免这种情况。任何人都知道为什么在 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>

【问题讨论】:

  • 我做了一些测试,这与hta无关,标准html文档也会出现错误。

标签: javascript object scope onbeforeunload hta


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 2012-04-22
  • 2015-01-14
  • 2016-03-17
  • 1970-01-01
  • 2022-08-10
  • 1970-01-01
  • 2011-11-23
  • 2015-11-05
相关资源
最近更新 更多