萬事開頭難,克服本身的拖延症,第一篇js基礎複習篇start!
但願和各位同行交流,同時歡迎各位指出不足和錯誤之處。javascript
對於一些基本類型,typeof是能夠判斷出數據類型,可是判斷一些引用類型時候,不能具體到具體哪種類型
再來複習一下typeof的用法:java
// 基本類型 typeof 123; //number typeof "123"; //string typeof true; //boolean typeof undefined; //undefined typeof null; //object let s = Symbol; typeof s; //symbol // 引用類型 typeof [1,2,3]; //object typeof {}; //object typeof function(){}; //function typeof Array; //function Array類型的構造函數 typeof Object; //function Object類型的構造函數 typeof Symbol; //function Symbol類型的構造函數 typeof Number; //function Number類型的構造函數 typeof String; //function String類型的構造函數 typeof Boolean; //function Boolean類型的構造函數 複製代碼
var obj = [4,67,23]; obj instanceof Array; //return true obj.constructor == Array; // return true 複製代碼
爲何不許確?web
function Foo(name) { this.name = name; } var f = new Foo('zhangsan'); console.log(f instanceof Foo); //true console.log(f instanceof Object); //true 複製代碼
function Person() {}; function Student() {}; var p = new Person(); Student.prototype = p; var s = new Student(); console.log(s instanceof Student); //true console.log(s instanceof Person); //true 記憶: A instanceof C 等價於 A 是不是 C子類,或者後代? 複製代碼
判斷邏輯翻譯成js代碼以下:segmentfault
_instanceof(f, Foo); function _instanceof(L, R) { var R = R.prototype; var L = L.__proto__; while( true) { if(L == null) { return false; } if(L == R) { return true; } L = L.__proto__; } } 複製代碼
代碼以下:數組
var iframe = document.createElement('iframe'); document.body.appendChild(iframe); var arr = [1,2,3]; xArray = window.frames[0].Array; //iframe中的構造函數 var arrx = new xArray(4,5,6); console.log(arrx instanceof Array); //false console.log(arrx.constructor == Array);// false console.log(Array.prototype == xArray.prototype); //false console.log(arr instanceof xArray); //false console.log(arrx.constructor === Array);// false console.log(arr.constructor === Array);// true console.log(arrx.constructor === xArray);// true console.log(Array.isArray(arrx)); //true 複製代碼
解釋:紅寶書,p88瀏覽器
instanceof操做符的問題在於,它假定只有一個全局環境。若是網頁中包含多個框架,那實際上就存在兩個以上不一樣的全局執行環境,從而存在兩個以上不一樣版本的Array構造函數。
若是你從一個框架向另外一個框架傳入一個數組,那麼傳入的數組與在第二個框架中原生建立的數組分別具備各自不一樣的構造函數。bash
由於constructor能夠被重寫,因此不能確保必定是數組
example:markdown
var str = 'abc'; str.constructor = Array; str.constructor === Array // return true 複製代碼
而很明顯str不是數組。
並且constructor和instanceof存在一樣問題,不一樣執行環境下,constructor判斷不正確問題。app
最終肯定某個值究竟是不是數組,而無論它是在哪一個全局執行環境中建立的,這個方法的用法以下。框架
if(Array.isArray(value)){ return true; } 複製代碼
若是在還沒有實現isArray方法的瀏覽器中準確監測數組,咱們須要用到Object.prototype.toString方法來判斷,每個繼承自Object的對象都擁有toString的方法。
if(!Array.isArray){ Array.isArray = function(arg){ return Object.prototype.toString.call(arg)==='[object Array]' } } 複製代碼
本身能夠封裝一個獲取變量類型的函數
function getType(obj) { return Object.prototype.toString.call(obj).slice(8,-1); } var a = [1,2,3]; console.log(getType(a)); //Array var b = function(){}; console.log(getType(b)); //Function 複製代碼