typeScript--[es6class类实现继承]

2023-11-19

一.js中实现继承

// js实现继承
// 父类
function Father(name) {
    this.name = name
    this.say = function () {
        console.log(this.name + "在唱歌")
    }
}
var f = new Father("逍遥的码农")

// 子类
function Son(name) {
    Father.call(this, name)
}
Son.prototype = Father.prototype
var s = new Son("张三")
s.say()

二.ts中实现继承

// ts class类实现继承
// ts父类
class TsFather {
    name: string
    // 构造函数
    constructor(name: string) {
        this.name = name

    }
    say(): void {
        console.log(this.name + "在唱歌")
    }
}
var tsf = new TsFather("逍遥的码农")

// ts子类
class TsSon extends TsFather {
    constructor(name: string) {
        super(name)
    }
}
var tss = new TsSon("张三")
tss.say()

三.ts里的三种修饰符

(1)public:公有,在类里面、子类、类外面都可以访问(默认的就不做演示)

(2)protected:保护类型,在雷里面、子类里面可以访问,在类外部不能访问

(3)private:私有,在类里面可以访问,子类、类外边不能访问

protected:

class A {
    protected name: string
    constructor(name: string) {
        this.name = name
    }
}
var a = new A("张三")
console.log(a.name) //属性“name”受保护,只能在类“A”及其子类中访问。

private:

class A {
    private name: string
    constructor(name: string) {
        this.name = name
    }
}
var a = new A("张三")
class B extends A{
    constructor(name:string){
        super(name)
        
    }
    say():void{
        console.log(this.name) //属性“name”为私有属性,只能在类“A”中访问。
    }
}
var b = new B("李四")
b.say()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

typeScript--[es6class类实现继承] 的相关文章

随机推荐