isPrototypeOf&&getPrototypeOf

isPrototypeOf&&getPrototypeOf:https://www.cnblogs.com/giggle/p/5208199.html 

 

 

在JavaScript这个一切皆为对象的世界里,难免会判断原型链的问题。那么我们就有必要了解了解isPrototypeOf和getPrototypeOf这两个方法咯。

1、isPrototypeOf

isPrototypeOf

作用

我的理解:确定一个对象的原型链中是否继承了prototype

官方语言:Determines whether an object exists in another object's prototype chain.

用法

prototype.isPrototypeOf(object)

备注

如果object的原型链中有prototype,则返回true;否则,返回false

我们一起demo下,看看isPrototypeOf到底是个什么东东。

复制代码
复制代码
<!DOCTYPE html> 
    <head>
        <title>isPrototypeOf</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
        <script>
            function A(){
            
            }
            var a = new A();
            //通过A创建一个对象a,所以a的__proto__是指向A.prototype的
            console.log(A.prototype.isPrototypeOf(a));
            //A.__proto__是指向Object.prototype的
            console.log(Object.prototype.isPrototypeOf(A));
            //由于A.prototype的__proto__是指向Object.prototype的,所以a也就含有Object.prototype咯
            console.log(Object.prototype.isPrototypeOf(a));
            
        </script>
    </body>
</html>
复制代码
复制代码

运行上面的代码,截图chrome,如下

从上面的代码和chrome结果,可知isPrototypeOf的确是判断对象中的原型链是否继承了prototype。

2、getPrototypeOf

getPrototypeOf

作用

返回对象__proto__指向的原型prototype

用法

Object的静态方法,使用如下Object.getPrototypeOf(object)

还是如此,我们一起demo下

复制代码
复制代码
<!DOCTYPE html> 
    <head>
        <title>getPrototypeOf</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    </head>
    <body>
        <script>
            function Fn(){
            
            }
            var fn = new Fn();
            //通过getPrototypeOf静态方法,获得对象fn的prototype
            var proto = Object.getPrototypeOf(fn);
            //将获得的prototype添加一个name属性,并赋值
            proto.name = 'Monkey';
            //输出对象fn.name
            console.log(fn.name);
            //判断proto是否是Fn.prototype
            console.log( 'proto === Fn.prototype? ' + (proto === Fn.prototype) );
            //判断fn的__proto__是否指向了prototype
            console.log( proto.isPrototypeOf(fn));
        </script>
    </body>
</html>
复制代码
复制代码

执行上面的代码,截图chrome,如下

从上面的代码和结果图,可得:

getPrototypeOf,的确是返回对象__proto__指向的prototype。

posted on   byd张小伟  阅读(136)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示