JavaScript语言基础---函数细节继续

来源:互联网 发布:闪电VPN软件怎么样 编辑:程序博客网 时间:2024/05/20 13:40
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JavaScript语言基础---函数细节继续</title>
</head>
<body>
<input type="button" onclick="demo1()" value="执行函数1">
<input type="button" onclick="demo2()" value="执行函数2">
<input type="button" onclick="demo3()" value="执行函数3">


<script type="text/javascript">
function hello() {
alert("hello....");
return;
}
function demo1() {
//alert(hello());//1.执行hello()输出hello..  2.把hello()方法的返回值用alert()弹出,此时为:undefined
//alert(hello);
//function hello() {alert("hello....");}//输出函数对象hello的toString()---函数定义的特征串
//alert(hello.toString());
alert(hello().toString());////1.执行hello()输出hello..  
}
</script>


<script type="text/javascript">
//匿名函数
//2.匿名函数
/*
function abc(a,b){
  return a+b;
}
var add = abc;

function demo2(){
  alert( add(1,2) );
  alert( abc(10,20) );
}
*/
var add = function(a, b) {//创建一个匿名函数
return a + b;
};
function demo2() {
alert(add(1, 2));
}
</script>
<script type="text/javascript">
//匿名函数实例---以后我们对页面组件的事件重新赋予动作时,通常采用匿名函数的方式赋
function demo3() {
var btn1 = document.getElementsByTagName("input")[0];
btn1.onclick = function() {//把第一个按钮的内容修改
alert("ok");
};
}
document.write("<br/>");
</script>


<script type="text/javascript">
/*3.变量的作用域1:在js中,一个变量定义之后,它的作用域不是以大括号来区
           分的,不但在本段脚本有效,而且在整个页面的所有脚本段中都是有效的
     ---这个概念就是全局变量
*/
for ( var i = 0; i < 10; i++) {//全局变量
document.write("i=" + i + "&nbsp;&nbsp;");


}
document.write("<br/>");
document.write("i2=" + i);
</script>


<script type="text/javascript">
document.write("i=" + i + "<br/>");
</script>


<script type="text/javascript">
 /*3.变量的作用域2:在函数中定义的变量是局部变量,在函数外面是不能访问的。
            一个细节:一个变量若声明但没赋值,它的值是undefined(由js默认帮我们初始化的值)。
                           如果一个变量没有声明就使用,在语法是挂的---语法错误!
          */
function show(){
var x=6;
x++;
document.write("x="+x+"<br/>");
}
show();
//document.write("x="+x+"<br/>");//因为变量x没有定义,,函数中定义的是局部变量,在这里访问不到。

var y=2;//全局变量
 function change(y){//形参y是局部变量,更改之后,不影响外面的实参
 y++; 
 //alert("yyyyy:"+y); //3
 }
 change(y);//实参
 document.write("y="+y+"<br/>");//2
</script>
</body>
</html>
0 0
原创粉丝点击