isPrototypeOf 与 instanceof区别

1、代码

<!DOCTYPE html>
<html lang="zh">

    <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>isPrototypeOf 与 instanceof区别</title>
    </head>

    <body>

        <script type="text/javascript">
            function Foo() {}

            function Bar() {}

            function Baz() {}

            Bar.prototype = Object.create(Foo.prototype);
            Baz.prototype = Object.create(Bar.prototype);

            var baz = new Baz();

            console.log(Baz.prototype.isPrototypeOf(baz)); // true
            console.log(baz instanceof Baz) // true

            console.log(Bar.prototype.isPrototypeOf(baz)); // true
            console.log(baz instanceof Bar) // true

            console.log(Foo.prototype.isPrototypeOf(baz)); // true
            console.log(baz instanceof Foo) // true

            console.log(Object.prototype.isPrototypeOf(baz)); // true
            console.log(baz instanceof Object) // true
        </script>
    </body>

</html>

2、区别

isPrototypeOf() 方法用于测试一个对象是否存在于另一个对象的原型链上。

isPrototypeOf() 与 instanceof 运算符不同。在表达式 "object instanceof AFunction"中,object 的原型链是针对 AFunction.prototype 进行检查的,而不是针对 AFunction 本身。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/isPrototypeOf

原文地址:https://www.cnblogs.com/mengfangui/p/10517599.html