萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript typeof 與 constructor 屬性類型判斷差異解析

核心差異

值typeofconstructor
{}'object'Object
[]'object'Array
function(){}'function'Function
'str''string'String
123'number'Number
true'boolean'Boolean
new Custom()'object'Custom

關鍵觀察

  • typeof 只能區分原始型別與 object/function,無法區分陣列、Date、RegExp、自訂類別(皆回傳 'object')。
  • constructor 指向建構該實例的函數,能精確識別 Array、Date、自訂類別等。
  • 所有物件(含原始值包裝物件)皆有 constructor 屬性(繼承自原型鏈)。

程式碼驗證

function Person(name, age) { this.name = name; this.age = age; }

const d = {an: 'object'};
const a = ['apple', 'banana'];
const f = function() {};
const s = 'David';
const n = 33;
const b = true;
const o = new Object();
const person = new Person('Mark', 22);

console.log(typeof d, d.constructor);      // object, Object
console.log(typeof a, a.constructor);      // object, Array
console.log(typeof f, f.constructor);      // function, Function
console.log(typeof s, s.constructor);      // string, String
console.log(typeof n, n.constructor);      // number, Number
console.log(typeof b, b.constructor);      // boolean, Boolean
console.log(typeof o, o.constructor);      // object, Object
console.log(typeof person, person.constructor); // object, Person

進階判斷工具:Object.prototype.toString.call()

最可靠的內建類型檢測:

Object.prototype.toString.call([])       // "[object Array]"
Object.prototype.toString.call({})       // "[object Object]"
Object.prototype.toString.call(new Date) // "[object Date]"
Object.prototype.toString.call(/re/)     // "[object RegExp]"
Object.prototype.toString.call(null)     // "[object Null]"
Object.prototype.toString.call(undefined)// "[object Undefined]"

封裝通用 typeOf:

const typeOf = v => Object.prototype.toString.call(v).slice(8, -1).toLowerCase();
// typeOf([]) === 'array', typeOf(null) === 'null'

注意事項

  • constructor 可被竄改(obj.constructor = Foo),不可完全信任。
  • 不同瀏覽器對正則表達式的 typeof 表現不同:IE/Firefox 回傳 'object',Chrome/V8 回傳 'function'(ES2015 規範為 'object')。
  • null 的 typeof 為 'object'(著名 Bug),需額外 val === null 判斷。

總結

typeof 適合快速區分原始型別與函數;精確識別物件具體類型請用 Object.prototype.toString.call();constructor 可作為輔助參考但不可當唯一依據。

copyright © 萬盛學電腦網 all rights reserved