js中typeof 与instanceof的区别

1、typeof

  用来检测给定变量的数据类型,其返回的值是下列某个字符串

"undefined":变量未定义

"boolean":变量为布尔类型

"string":变量为字符串

"number":变量为数值

"object":变量为对象或null

"function":变量为函数

alert(typeof null) //返回"object"

特殊值null被认为是一个空的对象引用

2、instanceof

  无论什么类型的对象,typeof均返回"object",而instanceof可以检测某个对象是否是某一数据类型,或一个对象是否是另一个对象的实例,也可以在继承关系中判断一个实例是否属于它的父类型,其左操作数为待检测对象,右操作数为定力类的构造函数,返回值为布尔类型true或false

var stringObject = new String("hello world");
var str = "hello world"
alert(stringObject instanceof  String)//返回true
alert(str instanceof  String)//返回false,instanceof不认为原始值的变量是对象
alert([1,2] instanceof  Object)//返回true
alert(null instanceof  Object)//返回false
alert(1 instanceof Object)//返回false
alert(1 instanceof  Number)//返回false
alert(undefined instanceof  Object)//返回false

undefined、null、布尔值、数组和字符串都是原始值

function Person(){};
var person = new Person();
alert(person instanceof  Person)//返回true
function Animal(){};
function Person(){};
Person.prototype = new Animal();
var person = new Person();
alert(person instanceof  Animal);//返回true
原文地址:https://www.cnblogs.com/lhyhappy365/p/5817954.html