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
    
  • 相关阅读:
    一些专有名词词汇
    UE、UI、 IA和IxD傻傻分不清
    关于SNMP4J取值乱码解决方法
    个人推荐
    软件系统分类
    Ext 4.2树节点搜索功能
    android picke ui
    android 滚轮
    一、dialog.show()引起的android.view.WindowManager$BadTokenException错误
    fragment getactivity 为null解决
  • 原文地址:https://www.cnblogs.com/Minstrel223/p/12383377.html
Copyright © 2011-2022 走看看