typeScript--[es6class类实现继承]

一.js中实现继承

javascript 复制代码
// 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中实现继承

TypeScript 复制代码
// 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:

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

private:

TypeScript 复制代码
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()
相关推荐
Hao_Harrision37 分钟前
50天50个小项目 (React19 + Tailwindcss V4) ✨| AnimatedCountdown(倒计时组件)
前端·typescript·react·tailwindcss·vite7
ttod_qzstudio1 小时前
从 Switch-Case 到自注册工厂:优雅的驱动行为管理系统重构
重构·typescript·工厂模式
CodeCaptain17 小时前
CocosCreator3.8.x 解析Tiled1.4.x【瓦片图层、对象图层、图像图层、组图层】的核心原理
经验分享·游戏·typescript·cocos2d
树叶会结冰18 小时前
TypeScript---对象:不自在但实在
前端·javascript·typescript
江公望19 小时前
tsconfig配置文件增加“esModuleInterop“: true,有什么作用?
typescript
wordbaby1 天前
三个核心概念,帮你彻底打通 TypeScript 泛型
前端·typescript
guangzan1 天前
Zod:TypeScript 类型守卫与数据验证
ai·typescript·zod
军军君012 天前
Three.js基础功能学习四:摄像机与阴影
开发语言·前端·javascript·3d·typescript·three·三维
EndingCoder3 天前
安装和设置 TypeScript 开发环境
前端·javascript·typescript
一个处女座的程序猿O(∩_∩)O3 天前
现代前端开发的三大支柱:TypeScript、ESLint、Prettier 深度解析与完美协作
javascript·typescript