JavaScript中typeof和instanceof的区别

时间:2021-01-07 14:51:39

 1、typeof

      typeof 是一个操作符,主要的目的是检测一个变量是不是基本数据类型的变量,同时也可以说是确定一个变量是字符串,数值,布尔值,还是undefined等的最佳工具。

     对一个值使用typeof操作符可能返回下列某种字符串:

  • “underfined”--如果这个值未定义
  • “boolean”--如果这个值是布尔值,即true或者false
  • “string”--如果这个值是字符串
  • “number”--如果这个值是数值
  • “object”--如果这个值是对象或null
  • “function”--如果这个值是函数
  • “symbol”--ES6新增
下面通过输出结果来验证一下:
console.log(typeof Symbol());    //"symbol"  es6新增
console.log(typeof Number()); //"number"
console.log(typeof String()); //"string"
console.log(typeof Function()); //"function"
console.log(typeof Object()); //"object"
console.log(typeof Boolean()); //"boolean"
console.log(typeof null); //"object"
console.log(typeof undefined); //"undefined"
输出的结果是:
symbol
number
string
function
object
boolean
object
undefined

2、instanceof       instanceof用于判断一个变量是否某个对象的实例,如var a=new Array();alert(a instanceof Array);会返回true。 下面我举一个例子:
function Person(){};
var friend = new Person();
console.log(friend instanceof Object);//true
console.log(friend instanceof Person);//true
   在这个例子中,用instanceof操作符测试Object和Person返回true,因为friend是Person的实例,而Person是Object的子类,所以也会返回true。

3、typeof和instanceof的区别       其实typeof和instanceof的目的都是检测变量的类型,两个的区别在于typeof一般是检测的是基本数据类型,,而instanceof主要检测的是引用类型。