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
    
  • 相关阅读:
    String和StringBuffer相关
    ReactNative 2018了解一下
    发送验证码倒计时效果
    图片实际尺寸大小
    ES6(一)
    组件开发之选项卡-2
    (function(){代码})()自执行函数
    Vue组件学习之三
    Vue下拉菜单实例demo
    窗口大小左右拖动demo
  • 原文地址:https://www.cnblogs.com/Minstrel223/p/12383377.html
Copyright © 2011-2022 走看看