Javascript燈謎時間又來了...

<html><body>
<script type="text/javascript">
test("Before");
function test(m) 
{
    alert(m);
}
test("After");
</script>
</body></html>

以上的Code,Before與After都會出現嗎? 在我印象中,Javascript函數一定要先宣告才能呼叫,但顯然有點誤差! 在上面的例子中,test("Before");與test("After");都會順利執行!

不過,注意到了嗎? 我是說有誤差,而非記錯了。原因是函數宣告前呼叫的狀況,只適用在同一個Script Block下。再來看一個例子:

<html><body>
<input type="button" onclick="test('OK')" value="test">
<script type="text/javascript">
test("Before Block");
</script>
<script type="text/javascript">
function test(m) 
{ alert(m); }
</script>
<script type="text/javascript">
test("After Block");
</script>
</body></html>

在以上的例子中,test("Before Block");被放在之前的Script Block而導致出錯,但後方Script Block的test("After Block");則OK。順手再測了宣告函數前就標成<INPUT>的onclick事件,也是可行的。

Goggle到一篇不錯的文章,順便記下來。


Comments

Be the first to post a comment

Post a comment