zoukankan      html  css  js  c++  java
  • javascript之继承

    ES6语法实现

    class Animal {
        constructor(type, color) {
            this.type = type
            this.color = color
        }
        speak(word) {
            console.log(this.type + " says " + word)
        }
        colorIs() {
            console.log(`${this.type} is ${this.color}`)//ES6新的字符串拼接方式
        }
    }
    class Cat extends Animal {
        constructor(color) {
            super()
            this.type = "cat"
            this.color = color
        }
        speak() {
            console.log("cat says miao")
        }
        eat() {
            console.log("eat rats")
        }
    }
    let kitty = new Cat("yellow")
    kitty.speak()
    kitty.speak("mew")//js没有函数重载,子类的speak()会将父类的speak(word)覆盖
    kitty.eat()
    kitty.colorIs()
    

    输出:

    cat says miao
    cat says miao
    eat rats
    cat is yellow
    

    ES5原型链继承与构造器继承

    var Animal = function (type, color) {
        this.color = color;
        this.type = type;
        this.say = function () {
            console.log(`I am a ${this.color} ${this.type}`);
        }
    }
    var dog = new Animal("dog", "yellow");
    dog.say();
    
    var Cat = function (color) {
        this.color = color;
        this.type = 'cat';
        this.eat = function () {
            console.log(`${this.color} ${this.type} eats rat`);
        }
    }
    Cat.prototype = new Animal();
    var kitty = new Cat('pink');
    kitty.say();
    kitty.eat();
    
    var Human = function (type) {
        Animal.call(this, type, 'smart');
        this.make = () => {
            console.log(`${this.type} makes tools`);
        }
    }
    var liMing = new Human('Chinese');
    liMing.say();
    liMing.make();
    

    输出:

    I am a yellow dog
    I am a pink cat
    pink cat eats rat
    I am a smart Chinese
    Chinese makes tools
    
  • 相关阅读:
    input file 多张图片上传 获取地址 ——fileReader
    15个常用的javaScript正则表达式
    sublime-emmet
    AMD-requireJS
    jQuery-lazyload参数
    easyui 查询条件form 数据遍历
    导出excel设置金额格式
    html5页面添加时间戳
    创建枚举
    定义实体转json需要方法
  • 原文地址:https://www.cnblogs.com/Minstrel223/p/12383377.html
Copyright © 2011-2022 走看看