es6: 类的继承

es5中的仿类结构继承

        function Animal(name) {                    // 写一个动物类
    this.name = name;
    this.thirsty = 100;                    // 口渴属性 使用drink可以减少口渴读
    this.food = []                         // 食物属性 使用eat可以在数组中添加食物
}
Animal.prototype.drink = function() {      // 添加一个喝的方法 
    return this.thirsty -= 10;
}
Animal.prototype.eat = function(item) {    // 吃的方法
    this.food.push(item)
}
function Dog(name, breed) {                // 写一个小狗类
    Animal.call(this, name);               // call指向动物类
    this.breed = breed;                    // 叫的属性
}

// Dog.prototype = Animal.prototype; // 喝水方法添加上了 但wc.constructor指向Animal,wc.constructor应该指向自己的构造函数
// Dog.prototype.constructor = Dog;  // wc.constructor都指向了Dog 但new Animal().constructor也指向了Dog

Dog.prototype = Object.create( Animal.prototype ); // 创建一个空对象 Animal和Dog实例的constructor都指回了各自
Dog.prototype.constructor = Dog;                   // 这次只有Dog的实例constructor都指向Dog
Dog.prototype.bark = function() {
     console.log('旺旺~~')
}
let wc = new Dog('小旺财', '中华田园犬')           // 创造实例

      

es6中的class继承extends

super的使用

静态方法的继承

        class Animal {
     constructor(name) {
          this.name = name;
          this.thirsty = 100;
          this.food = []
      }
      drink() {
          return this.thirsty -= 10;
      }
      eat(item) {
          this.food.push(item)
      }
      // 静态方法的继承
      static Info() {                        // Animal.Info()和Dog.Info()都可以调用,被继承了
          console.log('我是一个静态方法')
      }
}
class Dog extends Animal {                   // Dog继承Animal
     constructor(name, breed) {
         super(name);                        // 需要先调用父类  super的使用
         this.breed = breed;                 // 先调用父类 才有this
     }
     bark() {
         console.log('嗷呜~~')
     }
}
let duoduo = new Dog('多多', '哈士奇')

      

继承内置构造函数

        class moviesList extends Array {     // moviesList继承数组属性
    constructor(name, ...movies) {   // ...当个元素拼接成一个数组
        super(...movies);            // ...当前元素还原成一个一个元素
        this.name = name;
     }
     add(movie) {
         this.push(movie)            // push 方法来自Array的继承
     }
     topStar(limit) {                // 排序 方法来自Array的继承
         return this.sort( (a, b) => {return a.star> b.star ? -1 : 1} ).slice(0, limit)
     }
}

// 构造函数传参
var movies = new moviesList('我最喜欢的电影',
            {name: '泰坦尼克号', star: 9.7},
            {name: '星际穿越', star: 9.8},
            {name: '流浪地球', star: 8.5},
            {name: '陈翔六点半之重楼别', star: 9.3}
)
movies.add({name:'小黄人', star: 9})

      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值