zoukankan      html  css  js  c++  java
  • js中的继承

     

    通过【某种方式】让一个对象可以访问到另一个对象中的属性和方法,我们把这种方式称之为继承

     

    第一类: 原型链的继承

    People.prototype.eyeColor = function(){ console.log('这是原型继承') }

    在原型对象上增加eyeColor方法,所有的实例都可以拥有这个方法。

    特点及缺点:

    1、所有的新实例都会共享父类实例的属性

    2、一个实例修改了原型属性,所有实例的原型属性都会被修改

    第二类 :借用构造函数

        function Animal(name, age, gender) {
            this.name = name;
            this.age = age;
            this.gender = gender;
        }
        function Person(name, age, gender, say) {
            this.name = name;
            this.age = age;
            this.gender = gender;
            this.say = function () {
            };
        }

    以上的代码借用构造函数实现

    function Animal(name,age){
        this.name=name;
        this.age=age;
    }
    function Person(name,age,address){
        Animal.call(this,name);
        //this.name=name;
        //this.age=age;
        this.address=address;
    }

    1、Animal(父类构造函数)的代码必须完全适用于Person(子类构造函数)

    2、构造继承只能继承父类的实例属性和方法,不能继承原型属性和方法

     

    第二类 :组合继承    借用构造函数+原型继承的方法

    1、通过改变this指向,借用构造函数实现子类对父类属性的继承;

    2、通过原型,让子类型,继承父类型中的方法。

    // 父类型
        function Person(name, age, sex) {
          this.name = name;
          this.age = age;
          this.sex = sex;
        }
    
        Person.prototype.sayHi = function () {
          console.log('大家好,我是' + this.name);
        }
    
        // 子类型
        function Student(name, age, sex, score) {
          // 借用构造函数实现对属性的继承,需要使用call改变this指向
          Person.call(this, name, age, sex);
    
          this.score = score;
        }
    
        // 通过原型,让子类型,继承父类型中的方法,
        Student.prototype = new Person();
        //这里不能用 Student.prototype = Person
        //;因为这样Student中私有的属性和方法,也会传入到父类Person中。
        Student.prototype.constructor = Student;
    //这一行是必须的,必须设置consturctor,此时 Student.prototype 中的constructor 被重写了,会导致 stu1.constructor === Person,所yi需要将 Student 原型对象的 constructor 指针重新指向 Student 本身构造函数 学生特有的方法
        Student.prototype.exam = function () {
          console.log('考试');
        }

     

     

  • 相关阅读:
    CSS布局:让页底内容永远固定在底部
    PHP+jQuery实现翻板抽奖
    【数据结构】Java 版本 链表常用操作
    【数据结构】Python3版本 链表常用操作
    Python爬虫学习第一记 (翻译小助手)
    2019年第十届蓝桥杯真题解析JavaC组 A.求和
    2019年第十届蓝桥杯真题解析Java C组 B 矩形切割
    Java 13天基础 06天map集合小练习(黑马程序员) 统计字符串中每个字符出现的次数 (经典面试题)
    2019年第十届蓝桥杯真题解析JavaC组 D: 质数
    Java 9天入门(黑马程序员) 课程收尾 学生管理系统 (9.13)
  • 原文地址:https://www.cnblogs.com/jwenming/p/14438188.html
Copyright © 2011-2022 走看看