zoukankan      html  css  js  c++  java
  • 原型链

     原型链

      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)
  • 相关阅读:
    安卓开发1-开发第一个安卓hello word
    安卓开发系列
    Php调用工行支付接口时的问题解决
    angular模块
    angular自定义指令基础
    ajax跨域问题
    angular要点总结
    JS闭包函数
    避开ie6使用float后再使用margin兼容的2种方法
    如何学习面向对象编程
  • 原文地址:https://www.cnblogs.com/asasas/p/9471292.html
Copyright © 2011-2022 走看看