zoukankan      html  css  js  c++  java
  • javascript 原型继承 与class extends 继承对比

     
    //父类 Animal
    function Animal (name) {
        this.name = name;
        this.sleep = function () {
            console.log(this.name + '正在睡觉!')
        }
    }
    
    //cat 是 Animal 的子类
    function Cat (name, age) {
        Animal.call(this, name);
        //子类 Cat 新增加的 成员 age eat()
        Cat.prototype.age = age;
        Cat.prototype.eat = function () {
            console.log(this.name + 'is cat ' + '正在吃东西' + ' my age is ' + this.age)
        }
    }
    
    
    //---------调用代码---------------------
    var animal_obj = new Animal('动物');
    animal_obj.sleep();
    
    var cat_obj = new Cat('猫', 10);
    cat_obj.sleep();
    cat_obj.eat();
    
    
    
    //-------------------------------------------------------class------------------------------------------------------------------
    //父类 Animal
    class Animal {
        constructor(name) {
            this.name = name;
        }
        sleep () {
            console.log(this.name + '正在睡觉!')
        }
    }
    
    
    //cat 是 Animal 的子类
    class Cat extends Animal {
        //构造函数
        constructor(name, age) {
            super(name); //super 选调用父类构造方法
            this.age = age; //子类新增属性成员 age
        }
        //子类新增属性成员 eat(), class定义的成员函数不须要用 this.,也不用 function
        eat () {
            console.log(this.name + 'is cat ' + '正在吃东西' + ' my age is ' + this.age)
        }
    }
    
    //---------调用代码---------------------
    var animal_obj = new Animal('动物');
    animal_obj.sleep();
    
    var cat_obj = new Cat('猫', 10);
    cat_obj.sleep();
    cat_obj.eat();
    //-------运行结果一模一样--------------------------
     
     
  • 相关阅读:
    2018ACM上海大都会赛 F Color it【基础的扫描线】
    2018大都会赛 A Fruit Ninja【随机数】
    两个数互质的概率
    【shell脚本学习-3】
    【mysql学习-1】
    【HCNE题型自我考究】
    【为系统营造的一个安全的环境】
    【nginx下对服务器脚本php的支持】
    【linux基于Postfix和Dovecot邮件系统的搭建】
    不同状态的动态路由协议对比
  • 原文地址:https://www.cnblogs.com/qinlongqiang/p/11495211.html
Copyright © 2011-2022 走看看