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()
    
  • 相关阅读:
    数组作为方法参数时的一些意外情况
    pack://application:,,,/
    WPF 使用WinForm Chart控件
    WPF 后台绑定样式
    在转换为 UTC 时大于 DateTime.MaxValue 或小于 DateTime.MinValue 的 DateTime 值无法系列化为 JSON
    LINQ_to_SQL语法及实例大全
    C#编码好习惯,献给所有热爱c#的同学
    C#中OpenFileDialog的使用
    NET 2.0(C#)调用ffmpeg处理视频的方法
    SQLite Mysql 模糊查找(like)
  • 原文地址:https://www.cnblogs.com/daixixi/p/11306015.html
Copyright © 2011-2022 走看看