JavaScript 類型研究 Object.prototype.toString.call

JavaScript的數據類型,想到的是7種基本數據類型

基本類型
Undefined
Null
Boolean
String
Number
Symbol
引用類型
Object

類型說明

有空再寫了~數組

type of 類型和 運行時類型

這就要從 Object.prototype.toString.call(obj)提及了。
Object.prototype.toString.call(obj)能夠檢測傳入對象obj的數據類型,可是他和經常使用的 type of 又有一些不一樣。spa

JavaScript 的對象類型都繼承自Object,可是每一個對象的toString會被改寫。prototype

能夠參考如下嘗試驗證過程code

let arr_0 = ['a', 1, 2]
console.log(arr_0.toString()) // a,1,2
console.log(Array.prototype.hasOwnProperty('toString')) // true 這裏還有toString 方法
delete Array.prototype.toString  // 刪除數組的toString方法
console.log(Array.prototype.hasOwnProperty('toString')) // false- 數組的toString已經被刪除了
console.log(arr_0.toString()) // [object Array]

因此,不一樣類型的數據在使用toString()方法的時候,會由於類在繼承Object的時候改寫了toString()方法,表現出不一樣的結果
整理了個表格備忘
image.png對象

有興趣的同窗能夠本身試一試下面的代碼blog

function getType2String(target) {
  return Object.prototype.toString.call(target)
}
console.table({
  null: { val: null, typeof: typeof null, toString: getType2String(null) },
  'Symbol(s1)': { val: Symbol('s1'), typeof: typeof Symbol('s1'), toString: getType2String(Symbol('s1')) },
  '[]': { val: [], typeof: typeof [], toString: getType2String([]) },
  '{}': { val: {}, typeof: typeof {}, toString: getType2String({}) },
  '(function(){})': { val: (function () { }), typeof: typeof (function () { }), toString: getType2String((function () { })) },
  1: { val: 1, typeof: typeof 1, toString: getType2String(1) },
  ab: { val: 'ab', typeof: typeof 'ab', toString: getType2String('ab') },
  true: { val: true, typeof: typeof true, toString: getType2String(true) },
  Object: { val: Object, typeof: typeof Object, toString: getType2String(Object) },
  'void 0': { val: void 0, typeof: typeof void 0, toString: getType2String(void 0) },
  undefined: { val: undefined, typeof: typeof undefined, toString: getType2String(undefined) },~~~~
})
相關文章
相關標籤/搜索