typeof
- 常用于判断基本数据类型
- 返回的结果是该变量类型的字符串
- typeof的返回值包括
'number' 'string' 'undefined' 'boolean' bigint symbol function object (不包含null)
typeof 1 === 'number'
typeof '' === 'string'
typeof undefined === 'undefined'
typeof true === 'boolean'
typeof BigInt(1) === 'bigint'
typeof Symbol() === 'symbol'
typeof (function(){}) === 'function'
typeof null === 'object'
Object.prototype.toString.call(null) === '[object Null]'
instanceof
- instanceof的返回值是true或false
- instanceof的判断逻辑是基于原型链
- 用于判断一个引用类型是否属于某构造函数
- 可以通过继承关系判断一个实例是否属于它的父类型
({}) instanceof Object
[] instanceof Object
(()=>{}) instanceof Object
new Date() instanceof Object
function Fn() { };
let f1 = new Fn();
let f2 = {};
f2.__proto__ = Fn.prototype;
f1 instanceof Fn
f2 instanceof Fn
class Person { }
class Student extends Person { }
console.log(new Student() instanceof Student);
console.log(new Student() instanceof Person);
手动实现instanceof
let myInstanceof = (a, b) => {
let L = a.__proto__;
let R = b.prototype;
while (true) {
if (L !== R) L = L.__proto__;
if (L === R) return true;
if (L === null) return false;
}
}
Object.prototype.toString.call()
- toString是Object原型上面的方法,Array,Function等作为Object的子类基于toString方法实现了重写,以达到针对不同类型数据调用toString方法返回不同的隐式转换结果\
"字符串".toString()
(100).toString()
(()=>{}).toString()
false.toString()
new Date().toString()
- Object.prototype.toString()方法内部会调用 [Symbol.toStringTag] 返回对象类型的默认字符串描述,
"[object xx]" xx则对应[Symbol.toStringTag]的结果, Object.prototype.toString()最终结果为 "[object xx]"的字符串
Object.prototype.toString.call("");
Object.prototype.toString.call(true);
Object.prototype.toString.call(1);
Object.prototype.toString.call([]);
Object.prototype.toString.call(function(){});
Object.prototype.toString.call(new Error());
Object.prototype.toString.call(/\d+/);
Object.prototype.toString.call(new Date());
Object.prototype.toString.call(new class {});