typeof 字符串 => 数据类型(undefined、 boolean、number、string等)
instanceof 原型 => true/false
// 检测数据类型返回[Object String]
Object.prototype.toString.call('1') // string
数据类型
基本数据类型:Undefined、Null、Boolean、Number、String
引用数据类型:Object
typeof
检测null时会返回object,
因为null类型的机器码全是0,
而typeof检测到后三位全是0的时候,会返回object
检测到object类型之后,会再次调用内部的一个[[call]]函数,如果有则返回function,否则返回object
let str = "asdf";
typeof返回string,栈类型存储
let str = new String("asdf")
typeof 返回object,堆类型存储
instanceof
通过原型链来检测,返回boolean值,true false
A instanceof B
A是否是B的实例对象
function instanceof(A,B){ let p=A while(p){ if(p===B.prototype){ return true } p=p._proto_ } return false }
typeof 返回的是数据的类型,instanceof返回的是布尔值
// instanceof 检测 bool: true false
// A instanceof B
console.log([] instanceof Array); // true
console.log({} instanceof Object); // true
console.log(new Date instanceof Date); // true
function Person(){};
console.log(new Person() instanceof Person); // true
console.log([] instanceof Object); // true
console.log(new Date instanceof Object); // true
console.log(new Person() instanceof Object); // true
// instanceof 原型链 A instanceof B true, B instanceof C true
// 儿子 爸爸 爷爷
if(typeof(val) !== undefined) {}
console.log(Object.prototype.toString.call('1')); // string
console.log(Object.prototype.toString.call([])); // Array
console.log(Object.prototype.toString.call('1') console.log(Object.prototype.toString.call('[]')
instanceof返回布尔值:true/false;
a instanceof b? // a对象是否是b实例化后的,instanceof是根据原型链进行检测的;
与typeof的区别:
1》输出结果不同,typeof输出数据类型(少了null,多了function,object判定方式根据是否有【call】,有call检测为function,无为object),instanceof输出布尔值
2》typeof监测引用类型为object,不准确
测试一下笔记
typeof:返回object,null,function,undefiend
instanceof:检测布尔值,Triue OR false
instanceof检测返回Boolean值 true false =>A instanceof B(A对象是否由B对象实例化出来的)
instanceof是按原型链进行查找的
//可以检测数据类型
object.prototype.tostring.call('1')//string
3.
typeof 和 instanceof的不同之处
2、检测某一个想要的数据的数据类型
Object.prototype.toString.call('1') //string
Object.prototype.toString.call([]) //Array 也是用来检测
typeof: 返回的是一个字符串,字符串用来说明类型,返回的结果有number,boolean,string,function(函数),object(Null,数组,对象),undefined,Null
instanceof: 判断A instanceof B A是否为B的实例对象 返回的是bool类型: true false
异同
instanceof 检测数据对象返回bool (true,false)
instanceof 判断A是否在B的原型链上
检测方法:
console.log(Object.prototype.toString.call('1')) // string
总结:typeof 和 instanceof检测数据类型的异同
typeof返回值是一个字符串,该字符串说明运算数的类型;结果为number,bollean,string,function(函数),object(null,数组,对象),undefined
instanceof 是用来判断A是否为B的实例化对象,检测的是原型 返回值是布尔值
instanceof 原型链 A instanceof B true,B instanceof C true
object.prototype.toString.call()检测数据是什么类型
typeof 返回值是一个字符串,该字符串说明运算数的类型;结果为number,boolean,string,function(函数),object(null,数组,对象),undefined.
instanceof是用来判断 A 是否为B 的实例对象,检测的是原型
typeof & instanceof
1、instanceof 检测 true或false 是由原型链来进行查找判断的,
A instanceof B A是否为B 的实力对象,检测的是原型
2、检测某一个想要的数据的数据类型
Object.prototype.toString.call('1') //string
Object.prototype.toString.call([]) //Array 也是用来检测
[] instanceof Object //true
[] instanceof Array // true
typeof 与instanceof的区别
typeof instanceof 异同