| 值 | typeof | constructor |
|---|---|---|
| {} | '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 可作為輔助參考但不可當唯一依據。