2012-01-13 21 views
0

這有點奇怪。我一直試圖從父對象調用一個子對象的函數,但它似乎超出了onbeforeunload函數的作用域。這些函數調用在onbeforeunload之外工作,因此只有在onbeforeunload中調用時纔會失敗。我可以通過將子對象設爲全局來修復它,但我試圖避免這種情況。任何人都知道爲什麼我的childobject在onbeforeunload調用時超出範圍?注意我在windows onload事件中調用了相同的函數,它工作正常。這裏是代碼:HTA Javascript - 爲什麼對象超出了onbeforeunload的範圍?

<!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 2012-01-13 22:34:48

回答

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 2012-01-13 23:15:13