zoukankan      html  css  js  c++  java
  • 寄生组合继承

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

    既然要实现继承定义一个父类

    //定义一个动物类

    function animal(name){

      //属性

    this.name=name || "animal";

      //实例方法

    this.sleep=function(){

      console.log(this.name+"动物";

      }

    }

    //原型方法

    animal.prototype.eat=function(food){

      console.log(this.name+"动物东黑"

    }

    寄生组合继承

    function Cat(name){

      animal.call(this);

      this.name=name || "Tom";

    }

    (function(){

      //创建一个没有实例方法的类

      var Super=function(){};

      Super.prototype=animal.protoType;

      //实例作为子类的原型

      Cat.prototype=new Super();

    })();

    执行

    var cat = new Cat();
    console.log(cat.name);
    console.log(cat.sleep());
    console.log(cat instanceof Animal); // true
    console.log(cat instanceof Cat); //true
  • 相关阅读:
    java常见异常
    实现两个整数变量交换
    java抽象类与接口
    Java内部类用法
    单例模式
    easyUI下拉列表点击事件的使用
    Java中使用HttpRequest获取用户真实IP地址端口
    js-easyUI格式化时间
    1124
    ACM算法
  • 原文地址:https://www.cnblogs.com/xiaohuanghua/p/10456758.html
Copyright © 2011-2022 走看看