標籤:關鍵字 形參 st3 orange 變數 lan logs har 參數
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>函數的使用</title> <script type="text/javascript"> //函數定義 //1,命名函數 //需要調用時才會執行 //需要加上function關鍵字 不需要寫傳回型別 也不需要形參 function add(num1,num2){ //在方法中定義的變數 局部變數 //可存取範圍僅限當前方法中 var result = num1+num2; //document.write(result+"<br/>"); //需要返回結果,返回結果 不需要就不返回,方法頭不需要改動 return result; } //2匿名函數,賦予一個變數值,通過變數來調用函數 var minus = function (num1,num2){ var result = num1-num2; return result; } //3 使用Function類的構造方法構造匿名函數 var mul = new Function("num1","num2","return num1*num2"); function test1(){ s1 = "newApple"; } var test2 = function(){ //如果有局部變數和全部變數同名, //在這個方法中使用的是局部變數 //想要使用外部的全域變數,需要加引用 window //直接寫的s1是上面的局部變數 s1 = "banana"; //局部變數 //局部變數不能在函數外使用 var s1 = "orange"; s1 = "peach"; } //在JS中 可以在一個函數中可以再定義一個函數 局部函數 function test3(){ document.write("test3被調用"+"<br/>"); function test4(){ document.write("test4被調用"+"<br/>"); } //局部函數只能在所定義的函數之內調用 test4(); } //函數調用 //1.直接通過方法名(實參) //add(1,2); document.write(add(1,2)+"<br/>"); document.write(minus(8,2)+"<br/>"); document.write(mul(8,2)+"<br/>"); //2.call方法調用(對象引用,參數1,參數2...) document.write(add.call(window,4,8)+"<br/>") //3.使用apply方法調用函數 document.write(add.apply(window,[2,8])+"<br/>"); //全域變數 直接定義的變數 //在整個指令碼都可以使用 var s1; s1 = "apple"; document.write("s1:"+s1+"<br/>") test1();//調用 document.write("s1:"+s1+"<br/>") test2(); document.write("s1:"+s1+"<br/>")//newApple test3(); </script></head><body></body></html>
HTML 函數的使用