1.window對象
在全局作用域下聲明的函數(shù)屬于window對象
function fn() {
console.log('測試函數(shù)')
}
window.fn()
使用var 關鍵字在全局作用域下聲明的變量也是屬于window對象
var num = 10
console.log(window.num)
2.延時器setTimeout
setTimeout 僅僅只執(zhí)行一次,平時省略window
開啟延時器:
let timerId = setTimeout(function () {
console.log('真的延時執(zhí)行了嗎?')
}, 1000)
關閉延時器:
clearTimeout(timerId)
3.常見異步任務
注冊事件
setTimeout setInterval
Ajax
promise
4.事件循環(huán) EventLoop
1.同步任務由 JavaScript 主線程依次來執(zhí)行
2.異步任務委托給宿主環(huán)境(瀏覽器)執(zhí)行
3.已完成的異步任務對應的回調函數(shù)和屎,會被加入到任務隊列中等待執(zhí)行
4.JavaScript 主線程的執(zhí)行棧被清空后碰煌,會讀取任務隊列中的回調函數(shù)
5.按次序執(zhí)行 JavaScript 主線程不斷重復上面的第 4 步
5.location對象
href屬性得到完整url地址
console.log(location.href)
設置href屬性值太雨, 進行頁面跳轉
location.href = 'http://www.reibang.com/'
search 屬性獲取查詢字符串蕊退,符號?及?后面部分
hash 屬性獲取哈希值验夯,符號 # 及 # 后面部分
reload 方法 用于刷新頁面
6.navigator對象
通過 userAgent 屬性檢測瀏覽器的版本及平臺
// 檢測 userAgent(瀏覽器信息)
(function () {
const userAgent = navigator.userAgent
// 驗證是否為Android或iPhone
const android = userAgent.match(/(Android);?[\s\/]+([\d.]+)?/)
const iphone = userAgent.match(/(iPhone\sOS)\s([\d_]+)/)
if (android || iphone) {
// 如果是Android或iPhone猖吴,則跳轉至移動站點
location.
}
})()
7.histroy對象
history.back() 后退一個歷史記錄
history.forward() 前進一個歷史記錄
history.go(0) 刷新頁面
history.go(3) 前進3個歷史記錄
history.go(-3) 后退3個歷史記錄
history.go(300) undefined 不生效
8.本地存儲
數(shù)據(jù)存儲在用戶瀏覽器中
只能存字符串
生命周期永久生效
頁面刷新頁面關閉不丟失數(shù)據(jù)
存儲數(shù)據(jù):localStorage.setItem('鍵', '值') 同鍵名有覆蓋效果
獲取數(shù)據(jù):localStorage.getItem('鍵')
刪除數(shù)據(jù):localStorage.removeItem('鍵')
復雜數(shù)據(jù)類型需轉成JSON字符串,再存儲到本地
//把js復雜數(shù)據(jù)字符串化得到 JSON字符串,再本地存儲
localStorage.setItem('data', JSON.stringify(obj))
//先取出本地存儲的JSON字符串,再將JSON字符串解析成JS的復雜數(shù)據(jù)
JSON.parse(localStorage.getItem('data'))
sessionStorage和 localStorage用法一樣
生命周期為關閉瀏覽器窗口
9.自定義屬性
操作自定義屬性的方法 了解即可
1.元素.getAttribute('屬性名')
2.元素.setAttribute('屬性名', '值')
3.元素.removeAttribute('屬性名')
規(guī)范自定義做法:
在標簽上使用data-* 來表示自定義屬性
在JS操作的時候,通過 元素.dataset 來進行操作挥转,返回一個對象
<div data-index="1" data-id="2" >哈哈</div>
let box = document.querySelector('#box')
console.log(box.dataset) //{index: '1', id: '2'}
console.log(box.dataset.index) // 1