-->

2011-11-24

javascriptのtry{...}catch(e){...}の変数eのスコープ

ブラウザによってcatch(e)のeの参照できる範囲が違うので、
finallyなどで代用できる場合はそうしたほうが良いかもしれない。

もしくはeのスコープが限定的になるように無名関数で囲む。
(function(){
  var e;
  try
  {
    ...;
  }
  catch(e)
  {
    ...;
  }
})();

もしくは"e"を予約語として扱う。
"for","if"のように変数名に使えないものとして扱う。
try,catchが入れ子になっていたら困るかもしれない。

Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
number : 1
number : 1
string : throw
number : 1
number : 2
number : 2

Firefox8の場合。catch(e){var e; ...} っぽい感じ。
Mozilla/5.0 (Windows NT 5.1; rv:8.0) Gecko/20100101 Firefox/8.0
number : 1
number : 1
string : throw
number : 1
number : 2
number : 2 

IE8の場合。var e; catch(e){...} っぽい感じ。
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
number : 1
undefined : undefined
string : throw
string : throw
number : 2
number : 1

ソース。
//<![CDATA[<!--
(function(){
var a=1, b=2;
document.write("<br>"+navigator.userAgent);
document.write("<br>"+typeof a+" : "+a);
(function(){
document.write("<br>"+typeof a+" : "+a);
try
{
throw "throw";
}
catch(a)
{
document.write("<br>"+typeof a+" : "+a);
}
document.write("<br>"+typeof a+" : "+a);
a=b;
document.write("<br>"+typeof a+" : "+a);
})();
document.write("<br>"+typeof a+" : "+a);
})();
//-->]]>

0 件のコメント: