目錄javascript
console.log(typeof 12); var name = 'xiaoke'; console.log(typeof name);
使用typeof檢測數據類型,首先返回的都是一個字符串,其次字符串中包含了對應的數據類型java
- 例如:"number"、"string"、"boolean"、"undefined"、"function"、"object"、""
侷限性: typeof null->"object"數組
- 不能具體細分是數組仍是正則,仍是對象中其餘的值,由於使用type哦對檢測數據類型,對於對象數據類型中的值,最後返回的結果都是"object"
console.log(typeof typeof typeoof function());//->"string" function fn(callback){ //typeof callback === "function"?callback:null; callback&&callback(); } fn(function(){});
var obj = [12,23]; console.log(obj instanceof Array);//true console.log(obj instanceof RegExp);//false
侷限性:瀏覽器
- 在類的原型繼承中,咱們最後檢測出來的結果不必定正確
在原型被修改以後均可能不正確函數
console.log(1 instanceof Number);//false console.log("" instanceof String);//false var ary = []; console.log(ary instanceof Array);//true function fn(){} var ary = new Array; fn.prototype = new Array;//->原型繼承;讓子類的原型等於父類的一個實例 var f = new fn; f.__proto__ = fn.prototype=ary.__proto__=Array.prototype; fn.prototype->Array.prototype->Object.prototype console.log(f instanceof Array);//true
做用和instanceof很是類似this
- 能夠處理基本數據類型的檢測
- constructor檢測Object和instanceof不同,通常狀況下是檢測不了的
侷限性:prototype
- 咱們能夠把類的原型進行重寫,在重寫的過程當中頗有可能出現以前的constructor給覆蓋了,這樣檢測出來的結果就是不正確的
var num = 1; console.log(num.constructor ===Number);// var reg = /^$/; console.log(reg.constructor===RegExp);//true console.log(reg.constructor===Object);//false function Fn(){} Fn.protoype = new Array; var f = new Fn; console.log(f.constructor);//Array
注意:對於特殊的數據類型,好比:null和undefined,他們的所屬類是Null和Undefined,可是瀏覽器把這兩個類保護起來了,不容許在外面訪問使用
什麼叫Object?code
- Object是內置類、是全部對象的基類、Object是引用數據類型
- 首先獲取Object原型上的toString方法,讓方法執行,而且改變方法中的this關鍵字
- 做用:Object.prototype.toString它的做用是返回當前方法的執行主體(方法中的
this
)所屬類的詳細信息,[object Object]
,第一個object表明當前實例是對象數據類型(這個是固定死的),第二個Object表明的是obj所屬類是Object
var obj = {}; console.log(obj.toString());//->toString中的this是誰?->obj,返回的是obj所屬類的信息->"[object Object]"
咋一看應該是轉換爲字符串,可是某些toString方法不單單是轉換爲字符串
對於Number、String、Boolean、Array、RegExp、Date、Function原型上的toString方法都是把當前的數據類型轉換爲字符串類型的(它們的做用僅僅是用來轉換爲字符串的)對象
- Number.prototype.toString()是用來轉換爲字符串的,若是toString()的參數爲一個,能夠轉換爲各類進制的數字
console.log(({}).toString());//[object Object]
繼承
- 字符串的原型上的toString()也是用來轉換爲字符串的,進制轉換無論用
console.log((1).toString());//Number.prototype.toString()轉換爲字符串 console.log((true).toString());//"true" console.log((null).toString());//Cannot read property''toString' of null console.log((undefined).toString());//Cannot read property''toString' of undefined console.log(({}).toString());//[object Object]