2012-01-13 5 views
0

これはちょっと変わったものです。親オブジェクトから子オブジェクトの関数を呼び出そうとしていましたが、onbeforeunload関数のスコープから外れているようです。これらの関数呼び出しは、onbeforeunloadの外部で動作するため、onbeforeunloadで呼び出された場合にのみ失敗します。子オブジェクトをグローバルにすることで修正できますが、私はそれを避けようとしていました。 onbeforeunloadで呼び出されたときに、私のchildobjectが範囲外になっている理由を知っている人は誰ですか?注意:私はWindows onloadイベントで同じ関数を呼び出すと正常に動作します。HTA Javascript - なぜオブジェクトは範囲外ですか?

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

私は、これがHTAに関連していない、いくつかのテストをしましたエラーは標準のhtml文書でも発生します。 – user1148592

答えて

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

http://stackoverflow.com/questions/8656774/why-this-is-not-point-to-js-global-scope-in​​-the-code-example/8656817#8656817に似ています – davin

関連する問題