2012-01-13 3 views
0

이것은 조금 이상한 것입니다. 부모 개체에서 자식 개체의 함수를 호출하려고했지만 onbeforeunload 함수의 범위를 벗어나는 것 같습니다. 이 함수 호출은 onbeforeunload 외부에서 작동하므로 onbeforeunload에서 호출 될 때만 실패합니다. 나는 자식 객체를 전역 객체로 만들어서 수정할 수 있지만 그것을 피하려고했다. 누군가가 내 childobject가 onbeforeunload에서 호출되었을 때 범위를 벗어난 이유를 알고 있습니까? 윈도우 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

관련 문제