一、typeof
(1)console.log(typeof 123); | number |
(2)console.log(typeof "123"); | string |
(3)onsole.log(typeof true); | boolean |
(4)console.log(typeof undefined); | undefined |
(5)console.log(typeof function(){}); console.log(typeof Array); | function |
(6)console.log(typeof {a:1}); console.log(typeof null); console.log(typeof [1,2,3]); console.log(typeof new Date()); | object |
1、typeof是如何检测的?
typeof会检测对应类型的机器码,以机器码的后三位判断所属类型
null的机器码后三位为000,因此typeof判定为object类型
关于null的类型被typeof判断为object为JavaScript语言的设计过程中的bug,已经有人提案修改...
2、上表第五行和第六行均为引用类型,但一个返回object,一个返回function?
typeof在检测到引用类型后,会检测是否存在call方法,如果存在则返回function,如果不存在则返回object。
3、"asdf"与new String("asdf");
let str = "asdf";
console.log(typeof str);//string
let str2 = new String("asdf");
console.log(typeof str2);//object
str为字面量方式创建字符串,str存储的是变量,存储位置在栈中
str2为构造函数方式创建字符串,str2存储的是地址,str2在栈中,它存储的地址指向堆中的内存,str2是一个引用类型
二、instanceof
console.log([] instanceof Array);
console.log({} instanceof Object);
console.log(new Date() instanceof Date);
function Person(){};
console.log(new Person() instanceof Person);
console.log([] instanceof Object);
console.log(new Date() instanceof Object);
console.log(new Person() instanceof Object);
instanceof原理与实现:instanceof原理与实现_SignalFire的博客-CSDN博客