instanceof与constructor的区别

时间:2023-03-09 16:25:14
instanceof与constructor的区别

名词介绍

instanceof 的作用是判断实例对象是否为构造函数的实例,实际上判断的是实例对象的__proto__属性与构造函数的prototype属性是否指向同一引用;

constructor 的作用是返回实例的构造函数,即返回创建此对象的函数的引用。

区别

先贴出代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Instanceof</title>
</head>
<body> </body>
<script>
// 创建植物plant类
var plant = function(name,where){
this.name = name;
this.where = where;
document.write(this.name + "喜欢" + this.where + "的环境<br>");
}
// 创建动物animal类
var animal = function(name,food){
this.name = name;
this.food = food;
document.write(this.name + "吃" + this.food + "<br>");
}
// new两个实例dog和cat
var dog = new animal("狗","骨头");
var cat = new animal("猫","鱼"); // new两个实例greenDill和hangBasket
var greenDill = new plant("绿萝","湿热");
var hangBasket = new plant("吊篮","温暖湿热");
</script>
</html>

  上边代码中的创建了两个函数,new了四个实例。

  instanceof    

instanceof与constructor的区别

  上图可以看出用 instanceof 判断出dog的构造函数是animal,这个结果是意料之中的,但为什么Object也是dog的构造函数呢?

  上篇文章(https://www.cnblogs.com/menggirl23/p/10088465.html)中提到了实例对象、构造函数、原型对象之间的关系,了解这几个之间关系的应该就能明白为什么Object也是dog的构造函数。

  因为构造函数animal的 prototype 也是一个对象,对象就有__proto__属性,就会沿着原型链一直往上找,直到__proto__:Object结束,所以才会有这样的结果。

  constructor   

  上边名词介绍中写到constructor返回的是创建此对象的函数的引用。

instanceof与constructor的区别

总结

  instanceof找到的是实例在原型链中所有的构造函数,不容易找到直接创建实例的构造函数;

  constructor找到的是构造函数只有一个,就是直接创建这个实例的构造函数,所以用constructor找实例的构造函数更严谨。

以上有任何不对的地方,欢迎大家指正!

-THE END-