一、typeof
typeof
操作符返回一个字符串,表示未经计算的操作数的类型。
类型 | 结果 |
---|---|
Undefined | "undefined" |
Null | "object" (见下文) |
Boolean | "boolean" |
Number | "number" |
BigInt(ECMAScript 2020 新增) | "bigint" |
String | "string" |
Symbol (ECMAScript 2015 新增) | "symbol" |
宿主对象(由 JS 环境提供) | 取决于具体实现 |
Function 对象 (按照 ECMA-262 规范实现 [[Call]]) | "function" |
其他任何对象 | "object" |
二、instanceof
instanceof
运算符用于检测构造函数的 prototype
属性是否出现在某个实例对象的原型链上。
// 定义构造函数
function C(){}
function D(){}
var o = new C();
o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false,因为 D.prototype 不在 o 的原型链上
o instanceof Object; // true,因为 Object.prototype.isPrototypeOf(o) 返回 true
C.prototype instanceof Object // true,同上
C.prototype = {};
var o2 = new C();
o2 instanceof C; // true
o instanceof C; // false,C.prototype 指向了一个空对象,这个空对象不在 o 的原型链上.
D.prototype = new C(); // 继承
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true 因为 C.prototype 现在在 o3 的原型链上
三、constructor
所有对象都会从它的原型上继承一个 constructor
属性
var o = {};
o.constructor === Object; // true
var o = new Object;
o.constructor === Object; // true
var a = [];
a.constructor === Array; // true
var a = new Array;
a.constructor === Array // true
var n = new Number(3);
n.constructor === Number; // true
四、Object.prototype.toString.call()
使用 Object 对象的原型方法 toString ,使用 call 改变指向,借用Object的 toString 方法,还可以写成({}).toString.call(),效果是一样的
Object.prototype.toString.call(value).slice(8, -1).toLowerCase()
Object.prototype.toString.call(null).slice(8, -1).toLowerCase()
// => 'null'
Object.prototype.toString.call(true).slice(8, -1).toLowerCase()
// => 'boolean'
Object.prototype.toString.call(1).slice(8, -1).toLowerCase()
// => 'number'
Object.prototype.toString.call([1, 2, 3]).slice(8, -1).toLowerCase()
// => 'array'
Object.prototype.toString.call({ a: 1 }).slice(8, -1).toLowerCase()
// => 'object'
Object.prototype.toString.call(new Set()).slice(8, -1).toLowerCase()
// => 'set'
Object.prototype.toString.call(new Map()).slice(8, -1).toLowerCase()
// => 'map'
Object.prototype.toString.call(function() {}).slice(8, -1).toLowerCase()
// => 'function'