码迷,mamicode.com
首页 > 其他好文 > 详细

isPrototypeOf&&getPrototypeOf

时间:2017-04-17 22:13:32      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:分享   oct   har   通过   type   静态方法   row   使用   href   

在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。

isPrototypeOf&&getPrototypeOf

标签:分享   oct   har   通过   type   静态方法   row   使用   href   

原文地址:http://www.cnblogs.com/chenshizhutou/p/6724870.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!