zoukankan      html  css  js  c++  java
  • isPrototypeOf&&getPrototypeOf

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

    如果喜欢本文,请点击右下角的推荐哦,谢谢~
    更多,见My微信公众号^.^
  • 相关阅读:
    反调试:ZwQueryInformationProcess
    反调试:检测类名与标题名
    对某个区间操作(sort,stable_sort,parital_sort,parital_sort_copy,nth_element,is_sorted)
    数值算法(accumluate,inner_product,partial_sum,adjacent_difference,power,itoa)
    随机重拍与抽样(random_shuffle,random_sample,random_sample_n)
    分割(partition,stable_partition)
    子序列匹配(search,search_n,adjcent_find,find,find_if,find_first_of,find_end)
    MySQL管理实务处理
    MySQL触发器
    MySQL使用游标
  • 原文地址:https://www.cnblogs.com/giggle/p/5208199.html
Copyright © 2011-2022 走看看