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()
相关推荐
Irene19919 小时前
TypeScript baseUrl 弃用解决(附:怎么在 Vite 中配置 resolve.alias)
typescript·vite·baseurl
蜗牛 Day Day Up12 小时前
vscode运行TypeScript
ide·vscode·typescript
We་ct13 小时前
LeetCode 136. 只出现一次的数字:线性时间+常量空间最优解拆解
前端·算法·leetcode·typescript·位运算
紫_龙1 天前
最新版vue3+TypeScript开发入门到实战教程之重要详解readonly/shallowReadOnly
前端·javascript·typescript
:mnong1 天前
Claude Code 项目设计分析
typescript·claude code
Cxiaomu1 天前
像ChatGPT一样逐字输出:React + TypeScript 流式接收与“打字机”效果实现方案
人工智能·react.js·chatgpt·typescript
We་ct1 天前
LeetCode 191. 位1的个数:两种解法详解
前端·算法·leetcode·typescript
坐吃山猪2 天前
TypeScript编程03-枚举
前端·javascript·typescript
阿珊和她的猫2 天前
TypeScript中const与readonly的区别与应用解析
javascript·typescript·状态模式
freewlt2 天前
Vue3 + TypeScript 项目架构设计:从 0 搭建企业级前端工程
前端·javascript·typescript