我们知道,Javacript脚本可以定义在三个地方,Head标签中,Body标签中,Body标签之后。当定义一个函数的时候,你是否考虑过你在页面上什么位置可以访问这个函数,有没有规律可循:
As we know, people can define javascript block in 3 places, the Head block, the Body block and after the Body block. When you define a function within each block, have you ever considered at where you can call this function. Is there any order to follow:
<html>
<head>
<title>
Pure Javascript test - Function Access Scope.
</title>
<script type="text/javascript">
console.log("Javascrript code in head1.");
</script>
<script type="text/javascript">
console.log("Javascrript code in head2.");
</script>
</head>
<body>
<script type="text/javascript">
console.log("Javascript code in body before div.");
Func1();
function Func1(){
console.log("I am Func1");
}
</script>
<div>
<h2>I am div between scripts in Body.</h2>
</div>
<script type="text/javascript">
console.log("Javascript code in body after div.");
Func1();
</script>
</body>
<script type="text/javascript">
console.log("Javascript code after body1.");
Func1();
</script>
<script type="text/javascript">
console.log("Javascript code after body2.");
Func1();
</script>
</html>
1. 定义在Head中第一个Script标签中的函数,可以被页面上任意Script标签内的脚本访问。
Functions defined in first script block in head, can be accessed by any script block in this page.
2. 定义在一个Script标签中的函数,可以被此Script标签中的任意脚本,和在此Script标签之下的定义的Script标签中的脚本访问。但是此函数不能被定义在此Script标签之上的Script标签中的脚本访问。
Functions defined in one script block, can be accessed within this block and blocks below, whereas they CAN NOT be accessed by blocks above current script block.