前端零碎知識點(二)

一、數據類型判斷

1、typeof

typeof返回一個數據類型的字符串,返回結果有number、boolean、string、object、undefined、function、symbol等7中類型,注意typeof不能判斷null和array;

typeof 66;  //number
typeof false;  //boolean
typeof 'hello world';  //string
typeof undefined;  //undefined
typeof new Function();  //function
typeof null;  //object
typeof [1,2,3];  //object
typeof new Date();  //object
typeof new RegExp();  //object

2、instanceof

instanceof 是用來判斷A是否爲B的實例,表達式爲:A instanceof B,如果A是B的實例,則返回true,否則返回false。注意instanceof不能檢測null和undefined;下面的三種說法是一個意思:

  1. 用於檢測構造函數的 prototype 屬性是否出現在某個實例對象的原型鏈;
  2. 用來測試一個對象在其原型鏈中是否存在一個構造函數的 prototype 屬性;
  3. 用來檢測 constructor.prototype 是否存在於參數 object 的原型鏈;
[1,2,3] instanceof Array;  //true
{} instanceof Object;  //true
new Date() instanceof Date;  //true
new RegExp() instanceof RegExp;  //true
null instanceof Null;  //報錯
undefined instanceof undefined;  //報錯

3、Object.prototype.toString.call()   (個人推薦)

Object.prototype.toString.call()方法能獲取準確的數據類型;

Object.prototype.toString.call('hello world');  //[object String]
Object.prototype.toString.call(12);  //[object Number]
Object.prototype.toString.call([1,2,3]);  //[object Array]
Object.prototype.toString.call(false);  //[object Boolean]
Object.prototype.toString.call(undefined);  //[object Undefined]
Object.prototype.toString.call(null);  //[object Null]
Object.prototype.toString.call(new Function());  //[object Function]
Object.prototype.toString.call(new Date());  //[object Date]
Object.prototype.toString.call(new RegExp());  //[object RegExp]

//由此可以寫一個準確判斷數據類型的函數
function checkType(value) {
    return Object.prototype.toString.call(value).slice(8,-1)
}

二、事件代理

由於事件會在冒泡階段向上傳播到父節點,因此可以把子節點的監聽函數定義在父節點上,由父節點的監聽函數統一處理多個子元素的事件。這種方法叫做事件的代理。

使用代理的優點:

1、代碼簡潔;

2、減少瀏覽器的內存佔用;

三、BOM操作

BOM(瀏覽器對象模型)是瀏覽器本身的一些信息的設置和獲取。

  • window.screen對象:包含有關用戶屏幕的信息
  • window.location對象:用於獲得當前頁面的地址(URL),並把瀏覽器重定向到新的頁面
  • window.history對象:瀏覽歷史的前進後退等
  • window.navigator對象:常常用來獲取瀏覽器信息、是否移動端訪問等等

獲取網址、協議、path、參數、hash

  • location.href  (同window.location.href)   獲取網址
  • location.protocol(同window.location.protocol)   獲取協議
  • location.pathname(同window.location.pathname)   獲取path
  • location.search(同window.location.search)   獲取參數
  • location.hash(同window.location.hash)   獲取hash

獲取UA      navigator.userAgent

瀏覽器的前進、後退功能    history.back()   history.forword()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章