zoukankan      html  css  js  c++  java
  • 类-继承

    类-继承

    继承可以让子类获得父类(基类)的方法、属性,可以扩充,增加新的方法和属性等

    extends

        class P {
            constructor(name,age) {
                this.name = name
                this.age = age
            }
            say () {
                console.log(this.name)
            }
    
        }
    
        class L extends  P {
            constructor(name,age,sex,hobby) {
                super(name,age)
                this.sex = sex
                this.hobby = hobby
            }
            say() {
                console.log(`${this.name} + ${this.hobby}`)
            }
        }
    
    
        let p = new P ("xiaoming",32)
        p.say() //xiaoming
    
        let l = new L("kangkang",23,"man","唱歌")
        l.say() //kangkang + 唱歌
    
    
    

    子类中的方法和父类中重名时会以子类为准。

    super()作用

    1. 作为父类构造函数调用

      调用后子类可以得到父类的属性和方法(要在开头就调用)(将子类的this放在了父类的构造函数中运行一遍)

    2. 作为对象的方式调用

      1. 非静态方法中访问super -> 父类原型

      2. 在静态方法中访问super ->父类

        在调用super时,父类运行中this始终会是子类的this

        class L extends  P {
            constructor(name,age,sex,hobby) {
                super(name,age)
                this.sex = sex
                this.hobby = hobby
            }
            say() {
                console.log(`${this.name} + ${this.hobby}`)
            }
        }
        
    

    多态

    同一个接口,在不同情况下做不一样的事情(相同接口,不同表现)

        class L extends  P {
            constructor(name,age,sex,hobby) {
                super(name,age)
                this.sex = sex
                this.hobby = hobby
            }
            say() {
            		super.say() // 同一函数名不同结果
                console.log(`${this.name} + ${this.hobby}`)
            }
        }
        
    

    重载

    函数参数不同,进行不同操作

    ES5中类继承实现

    function P() {
            this.name = "kangang"
            this.gender = 2
            this.say = function () {
                console.log("我是父类的哦!")
            }
        }
        P.prototype.test = function() {
            console.log(`我是原型上的test方法!!!`)
        }
        function C() {
            P.call(this)
            this.name = "xiaojun"
            this.age = 21
        }
    
        var child = new C()
        child.say() //我是父类的哦!
        child.test() // child.test is not a function
        
        // 上面的解决方法是
        C.prototype = new P()
    
  • 相关阅读:
    ZW网络团队及资源简介
    ZW云推客即将登场
    “4K云字库”基本框架图
    Sketch 55 Beta版本探秘,看看都有什么新功能
    产品经理有哪些类型?
    电影票APP原型设计分享– Movie Booking
    旅游类App的原型制作分享-Klook
    UI行业发展预测 & 系列规划的调整
    原来这就是 UI 设计师的门槛
    摹客PS插件全新改版!—— 智能检测不对应的设计稿
  • 原文地址:https://www.cnblogs.com/daixixi/p/11306015.html
Copyright © 2011-2022 走看看