JavaScript-instanceof关键字

什么是 instanceof 关键字

instanceof 用于判断 "对象" 是否是指定构造函数的 "实例"。

先来看如下这一段代码,利用 instanceof 关键字来看看结果。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-instanceof关键字</title>
    <script>
        class Person {
            name = "BNTang";
        }

        let p = new Person();
        console.log(p instanceof Person);

        class Cat {
            name = "mm";
        }

        let c = new Cat();
        console.log(c instanceof Person);
    </script>
</head>
<body>
</body>
</html>

image-20210910113306405

运行结果如上,实例对象只有是指定对应的构造函数创建出来的才会返回 true 否则为 false

instanceof 注意点

只要构造函数的原型对象出现在实例对象的原型链中都会返回 true

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-instanceof关键字</title>
    <script>
        function Person(name) {
            this.name = name;
        }

        function Student(name, score) {
            Person.call(this, name);
            this.score = score;
        }

        Student.prototype = new Person();
        Student.prototype.constructor = Student;

        let stu = new Student();
        console.log(stu instanceof Person);
    </script>
</head>
<body>
</body>
</html>

image-20210910110432122

posted @ 2021-09-10 11:41  BNTang  阅读(145)  评论(0编辑  收藏  举报