zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    C++操作文件行(读取,删除,修改指定行)
    Windows注册表中修改UAC(用户账号控制)及批处理脚本
    Centos7.x 安装libevent2.x
    【Docker】:使用docker安装redis,挂载外部配置和数据
    【Docker】:使用docker安装mysql,挂载外部配置和数据
    开源定时任务框架Quartz(二)
    开源定时任务框架Quartz(一)
    Spring Boot系列教程十四:Spring boot同时支持HTTP和HTTPS
    数据结构与算法:单向链表实现与封装(有头)
    【C++札记】指针函数与函数指针
  • 原文地址:https://www.cnblogs.com/bydzhangxiaowei/p/11524144.html
Copyright © 2011-2022 走看看