JavaScript-isPrototypeOf属性

什么是 isPrototypeOf 属性

isPrototypeOf 用于判断一个对象是否是另一个对象的原型。

首先看如下这一段代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-isPrototypeOf属性</title>
    <script>
        class Person {
            name = "BNTang";
        }

        let p = new Person();
    </script>
</head>
<body>
</body>
</html>

在内存中的体现如下图。

image-20210910154021308

有了如上代码之后继续往下看,我们利用 isPrototypeOf 来判断一下 Person.prototype 这个对象是否是 p 对象的原型对象,代码如下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-isPrototypeOf属性</title>
    <script>
        class Person {
            name = "BNTang";
        }

        let p = new Person();
        console.log(Person.prototype.isPrototypeOf(p));
    </script>
</head>
<body>
</body>
</html>

经过如上图的原型链示例图可以看出,Person.prototype 确实是 p 这个实例对象的原型对象所以是 true 如下。

image-20210918101955640

为了进一步验证,在来一段代码,如下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-isPrototypeOf属性</title>
    <script>
        class Person {
            name = "BNTang";
        }

        let p = new Person();

        class Cat {
            name = "mm";
        }

        console.log(Cat.prototype.isPrototypeOf(p));
    </script>
</head>
<body>
</body>
</html>

如上的代码当中,定义了一个 Cat 类,我取出了 Cat 的原型对象,判断是否是 p 实例的原型对象,Cat 的原型对象与 p 没有半毛钱关系,所以为 false 如下。

image-20210918102724805

isPrototypeOf 注意点

只要调用者在传入对象的原型链上都会返回 true。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript-isPrototypeOf注意点</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(Person.prototype.isPrototypeOf(stu));
    </script>
</head>
<body>
</body>
</html>

image-20210918103511956

image-20210918104330999

posted @ 2021-09-10 15:42  BNTang  阅读(124)  评论(0编辑  收藏  举报