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();
    //-------运行结果一模一样--------------------------
     
     
  • 相关阅读:
    寒假特训——搜索——H
    寒假特训——I
    寒假训练——搜索 K
    three.js 加载STL文件
    three.js 加载3DS 404 文件找不到
    C# 请求数据 方式1
    学习 一个简单的业务处理
    ABP 05 创建Model 以及 相应的增删改查
    ABP 04 用户的创建
    ABP 00 常用知识
  • 原文地址:https://www.cnblogs.com/qinlongqiang/p/11495211.html
Copyright © 2011-2022 走看看