var操作符定义的变量将成为定义该变量的作用域的局部变量,有2个例子:
1:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>无标题文档</title>
- </head>
- <body>
- <script type="text/javascript">
- var b = '111';
- function a() {
- return b;
- }
- alert(a());
- </script>
- </body>
- </html>
b定义于整个<script>标签内所以结果能弹出111
2:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>无标题文档</title>
- </head>
- <body>
- <script type="text/javascript">
- //var b = '111';
- function a() {
- var b = '111';
- //return b;
- }
- //alert(a());
- a();
- alert(b);
- </script>
- </body>
- </html>
运行结果为:
ReferenceError: b is not defined
file:///D:/Users/yj/Desktop/CDATA.html
Line 18
当省略var操作符时,将创建一个全局变量:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>无标题文档</title>
- </head>
- <body>
- <script type="text/javascript">
- //var b = '111';
- function a() {
- b = '111';
- //return b;
- }
- //alert(a());
- a();
- alert(b);
- </script>
- </body>
- </html>
结果同样能弹出111
转载于:https://blog.51cto.com/xhyujian/1097767