一、封閉函數(shù)
-
1.1、封閉函數(shù)定義:javascript中匿名函數(shù)的另外一種寫法,創(chuàng)建一個一開始就執(zhí)行而不用命名的函數(shù)
-
一般定義的函數(shù)和執(zhí)行函數(shù):
function myalert(){ alert('hello!'); }; myalert(); -
封閉函數(shù)寫法一:去掉函數(shù)名字,用括號抱起來,加上小括號執(zhí)行
(function myalert(){ alert('hello!'); })(); -
封閉函數(shù)寫法二:可以在函數(shù)定義前加上
“~”和“!”等符號來定義匿名函數(shù)!function myalert(){ alert('hello!'); }()或者
~function myalert(){ alert('hello!'); }()
-
-
1.2、封閉函數(shù)的好處:封閉函數(shù)可以創(chuàng)造一個獨立的空間,在封閉函數(shù)內定義的變量和函數(shù)不會影響外部同名的函數(shù)和變量,可以避免命名沖突,在頁面上引入多個js文件時,用這種方式添加js文件比較安全,比如:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>封閉函數(shù)的好處</title> <script type="text/javascript"> var iNum1 = 10; function myalter() { alert('hello'); } ~function () { var iNum1 = 20; function myalter() { alert('hello world!'); } alert(iNum1); myalter(); }(); alert(iNum1); myalter(); </script> </head> <body> </body> </html>提示:我們可以看到封閉函數(shù)里面的函數(shù)
myalter并不會把封閉函數(shù)外的函數(shù)myalter給屏蔽掉
二、常用內置對象
-
2.1、document
-
通過
id獲取元素document.getElementById -
通過
標簽名獲取元素document.getElementsByTagName -
獲取
上一個跳轉頁面的地址(需要服務器環(huán)境)document.referrer
-
-
2.2、location
-
獲取或者重定url地址
window.location.href -
獲取地址參數(shù)部分
window.location.search如下例子:
<script type="text/javascript"> window.onload = function () { // 根據(jù)id獲取一個按鈕的標簽 var oButton = document.getElementById('button1'); var aData = window.location.search; if (aData != ''){ alert(aData.split('=')); } } </script> -
獲取頁面錨點或者叫哈希值
window.location.hash
-
-
2.3、Math 對象
-
Math.random之能獲取0-1的隨機數(shù),不包括 1alert(Math.random()); -
Math.floor向下取整: 結果是:3alert(Math.floor(3.4)); -
Math.ceil向上取整: 結果是:4alert(Math.ceil(3.4));提示:向上或者向下取值是
沒有四舍五入的
-
-
2.4、舉例:生成 10-20之間的隨機數(shù)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>生成10到20的隨機數(shù)</title> <script type="text/javascript"> var iNum1 = 10; var iNum2 = 20; var array2 = []; for(var i=0;i<20;i++){ // 生成10-20之間的隨機數(shù) var iNum02 = Math.floor((iNum2-iNum1+1)*Math.random()) + iNum1; array2.push(iNum02); } console.log(array2); </script> </head> <body> </body> </html>打印結果: 15、20、11、16、18、20、20、20、18、16、17、20、12、14、13、11、17、17、17、13
三、調試 js 的方法
-
3.1、alter 調試比較直觀
var iNum1 = 10; alert(iNum1); -
3.2、console.log 在數(shù)據(jù)較多的時候可以直接展示出來,打印出來查看比較方便,比如上面的打印一個數(shù)組
console.log(array2); -
3.3、document.tittle 可以直接顯示在網頁的標題上,如下
document.title = "測試";
