zoukankan      html  css  js  c++  java
  • js实现继承

    js作为一种弱类型语言,继承也是其较大的功能之一

    首先定义一个父类

    // 定义一个教师类
    function Teacher (name) {
      // 属性
      this.name = name || 'Jack';
      // 实例方法
      this.study= function(){
        console.log(this.name + '正在学习!');
      }
    }

    一:继承的方式

    1,原型链继承:将父类的实例作为子类的原型

    function Student(){ 
    }
    Student.prototype = new Teacher();
    Student.prototype.name = 'john';

    测试
    var student = new Student();
    console.log(student.name);

    2,构造继承 (call,apply) 使用父类的构造函数来增强子类的实例,等同于复制父类的实例属性给子类

    function Student(name) {
      Teacher.call(this);
      this.name = name || "Tom"
    }

    var student = new Student();
    console.log(student.name);

    3,实例继承:为父类实例增加新特性作为子类实例返回

    function Student(name){
      var instance = new Teacher();
      instance.name = name || 'Tom';
      return instance;
    }
    
    // 测试
    var student = new Student();
    console.log(student.name);

    4,拷贝继承
    function Student(name){
      var teacher= new Teacher();
      for(var p in teacher){
        Student.prototype[p] = Teacher[p];
      }
      Student.prototype.name = name || 'Tom';
    }
    
    // 测试
    var student= new Student();
    console.log(student.name);

    5,组合继承 (通过调用父类的构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用

    function Student(name){
      Teacher.call(this);
      this.name = name || 'Tom';
    }
    Student.prototype = new Teacher();
    
    // 测试
    var student = new Student();
    console.log(student.name);

    6,寄生组合继承    通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的组合继承的缺点

    function Student(name){
      Teacher.call(this);
      this.name = name || 'Tom';
    }
    (function(){
      // 创建一个没有实例方法的类
      var Super = function(){};
      Super.prototype = Teacher.prototype;
      //将实例作为子类的原型
      Student.prototype = new Super();
    })();
    
    // 测试
    var student = new Student();
    console.log(student.name);
     
     
     
  • 相关阅读:
    论云端智能相册应用的架构设计及应用
    《架构漫谈》阅读笔记02
    论软件体系架构之质量属性
    《架构漫谈》阅读笔记01
    tensorflow-gpu:Could not load dynamic library 'cusolver64_10.dll'; dlerror: cusolver64_10.dll not found
    tensorflow线性回归
    【阿里巴巴国际站】22届实习生招聘开始啦!
    vue-ref、js获取dom子元素
    echarts地图tooltip添加标注
    echarts 图表坐标axisLabel格式化文字
  • 原文地址:https://www.cnblogs.com/shmily-code/p/7808608.html
Copyright © 2011-2022 走看看