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()
相关推荐
摸鱼仙人~7 小时前
如何创建基于 TypeScript 的 React 项目
javascript·react.js·typescript
一生躺平的仔1 天前
TypeScript入门(九)装饰器:TypeScript的"元编程超能力"
typescript
MiyueFE1 天前
让我害怕的 TypeScript 类型 — — 直到我学会了这 3 条规则
前端·typescript
前端拿破轮1 天前
😭😭😭看到这个快乐数10s,我就知道快乐不属于我了🤪
算法·leetcode·typescript
前端_ID林1 天前
每个开发人员都应该知道的 TypeScript 技巧
typescript
奋飛1 天前
TypeScript系列:第六篇 - 编写高质量的TS类型
javascript·typescript·ts·declare·.d.ts
BillKu11 天前
Vue3 + TypeScript + xlsx 导入excel文件追踪数据流转详细记录(从原文件到目标数据)
前端·javascript·typescript
小Lu的开源日常11 天前
Drizzle vs Prisma:现代 TypeScript ORM 的深度对比
数据库·typescript·前端框架
Shixaik11 天前
配置@为src
typescript·前端框架
BillKu12 天前
Vue3 + TypeScript合并两个列表到目标列表,并且进行排序,数组合并、集合合并、列表合并、list合并
vue.js·typescript·list