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();
    //-------运行结果一模一样--------------------------
     
     
  • 相关阅读:
    立体匹配算法(转载)
    校招总结
    tcpip概述
    Matlab2014a 提示未找到支持的编译器或 SDK的解决方法
    CSS3 实现简单轮播图
    css3实现switch开关效果
    Sass的使用和基础语法
    Git的安装和使用记录
    jQuery淡入淡出效果轮播图
    JavaScript焦点轮播图
  • 原文地址:https://www.cnblogs.com/qinlongqiang/p/11495211.html
Copyright © 2011-2022 走看看