JavaScript 里面的 instanceof 解析

  一般我们判断某个变量是什么类型的常常会用 typeof 运算符,但是你们发现没有,不管引用的是什么类型的对象,它都返回的是 object 类型的。其实有的时候我们很想看看这个对象是什么具体的类型,所以在JS里面引入了 instanceof 运算符。instanceof运算符跟typeof运算符很相似,都是用来查看类型。

  我们先说一下 typeof  和 instanceof 的语法:   

  对于 typeof :   typeof option

  option 是需要检测的对象,也可以是一个表达式,以字符串的形式返回 option 的类型。

  对于 instanceof : option  instanceof  constructor

  option 是需要检测的对象,constructor  是你确定的对象,返回的是这个option是否属于constructor这个类型的布尔值。看一个简单的例子:

function Student() { }
var studentA = new Student();
 
console.info(studentA instanceof Student)  //true
console.info(typeof studentA)              //'object'
console.info(typeof {k:1})                 //'object'
console.info(typeof 300)                   //'Number'
console.info(typeof 'hello world')         //'string'
console.info(typeof a!='undefind')         //true

  发现没有?虽然instanceof可能没有 typeof 那么好用,那么容易想到用,而且还可以用typeof来判断一个变量是否存在而不用if判断,但是instanceof必须要知道对比的那个类型(这里是constructor)。但是在对于typeof 一个对象的时候(也就是返回值为object的时候),instanceof 所体现的好处还是很大的。比如在继承当中可以明显看到优点:

function Person() { }  
Student.prototype = Object.create(Person);
Student.prototype.constructor = Student;

console.info(studentA instanceof Student)   //true
console.info(studentA instanceof Person)    //false 

  本文主要讲instanceof ,对于typeof就不再过多讲解。通常情况下,我们使用 instanceof 就是为了判断某个实例是否属于某种类型。例如上面的: 

studentA instanceof Student   //判断studentA 是否属于Student类型的

  书上曾经这么说的:instanceof 运算符可以用来判断某个构造函数的prototype属性是否存在另外一个要检测对象的原型链上。也就是说用来判断constructor.prototype是否存在于参数option的原型链上(对于JS里面的原型链,我这里就不讲解)。再看一个例子:

function My(){}
function You(){}
     
var myOne = new My();
console.info(myOne instanceof My)//true
console.info(myOne instanceof You)//false
 
My.prototype = {};  //修改了My.prototype
var myTwo = new My();
console.info(myTwo instanceof My)//true
console.info(myOne instanceof My)//false,My.prototype指向了空
 
You.prototype = new My();  //修改了Your.prototype
var myThree = new You();
console.info(myThree instanceof You)//true
console.info(myThree instanceof My)//true

 当在继承的这种情况下的时候或者要判断实例的类型的时候,明显使用instanceof会比typeof会更好。

原文地址:https://www.cnblogs.com/balabala/p/4273989.html