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
    
  • 相关阅读:
    编码和字符串
    表格边框总结
    自信
    jQuery入门知识点
    ASP.NET MVC路径引用总结
    JavaScript读书笔记(6)-Function
    JavaScript读书笔记(6)-Array RegExp
    JavaScript读书笔记(5)-Object Date
    python 常见的特殊方法
    pipreqs 找当前项目依赖的包
  • 原文地址:https://www.cnblogs.com/Minstrel223/p/12383377.html
Copyright © 2011-2022 走看看