• 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('考试');
        }

     

     

  • 相关阅读:
    C#中线程安全的单例模式
    分布式服务和库表设计模式详解
    通俗易懂的讲解下Java注解
    MEF框架使用总结
    Docker:四、Docker进阶 Windows Docker IIS 部署
    Docker:三、深入Docker容器&Asp.net发版
    Docker:二、开始部署第一个Asp.net应用
    Docker:一、开始部署第一个Asp.net应用
    Docker:常见命令
    .net 中的 StringBuilder 和 TextWriter 区别
  • 原文地址:https://www.cnblogs.com/jwenming/p/14438188.html
Copyright © 2020-2023  润新知