• 原型链


     原型链

      1. 每一个实例都有自己的原型,可以__proto__访问
      2. 构造函数,通过new创建实例
      3. 构造函数通过prototype指向原型对象
      4. 原型对象通过constructor指向构造函数
      5. 如下图所示:
      6. 访问对象中的属性,如果不存在,那么会在原型中查找,如果还没有,继续在原型中查找
        1. 继承

        1 构造函数

        1
        2
        3
        4
        5
        6
        7
        function Parent(name) {
            this.name = name
        }
        function Child(age) {
            Parent.call(this);
            this.age = age
        }

          

        2 原型链

        child.prototype = new Parent()
        缺点:当存在引用类型的时候,一个实例数据的改变,另一个也会改变,例如 P1.friend = ['Jany', 'LiMINg'],当P1增加一个朋友,另外的实例也会增加。

        3 组合继承

        把公共数据放在Parent中,这样的话就不会公用一个引用类型

        复制代码
        1 function Parent(name) {
        2     this.name = [‘Jang’,‘Dany’]
        3 }
        4 function Child(age) {
        5     Parent.call(this);
        6     this.age = age
        7 }
        8 child.prototype = new Parent()
        复制代码

        4 优化组合继承

        1
        2
        3
        4
        5
        6
        7
        8
        9
        function Parent(name) {
            this.name = [‘Jang’,‘Dany’]
        }
        function Child(age) {
            Parent.call(this);
            this.age = age
        }
        Child.prototype = Object.create(Parent.prototype)
        Child.prototype.constructor = Child

          

        判断原型和实例的关系

        1
        2
        3
        1. instance instanceof object,只要是原型链中的都可以
        2. object.prototyoe.isprototypeoof(instance)
        3. object.prototype.tostring.call(instance)
  • 相关阅读:
    JSP基础语法
    《进化:从孤胆极客到高效团队》的目录
    什么是Webpack
    程序猿看市场
    mysql多表关联更新
    Nginx+Tomcat配置集群session共享
    DOUBLE精度问题,BigDecimal
    程序员是否该这样
    Spring上传文件报错
    Emoji表情符号录入MySQL数据库报错的解决方案
  • 原文地址:https://www.cnblogs.com/asasas/p/9471292.html
Copyright © 2020-2023  润新知