怎样理解 instanceof

instanceof 运算符用来判断一个对象在其原型链中是否存在一个构造函数的 prototype 属性。

也就是说, instanceof 判断的实际上是某个对象是否为某个构造函数的实例, 因为es5中没有类的概念, 这里的instanceof其实是充当了一个判断类的实例对象的功能.

比如下面的两个例子:

document.getElementsByTagName() 返回一个类似数组的对象, 这个对象是 HTMLCollection 这个构造函数的实例. 

而 document.querySelectorAll() 返回一个类似数组的对象, 这个对象是 NodeList 这个构造函数的实例. 

<!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>Document</title>
</head>
<body>
    <ul>
        <li>李雷</li>
        <li>韩梅梅</li>
        <li>李强</li>
        <li>徐帆</li>
    </ul>
    <script>
        document.getElementsByTagName("li") instanceof HTMLCollection; // true
        document.querySelectorAll("li") instanceof NodeList; // true
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/aisowe/p/11511349.html