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()
相关推荐
林鑫_14 分钟前
面向JavaScript程序员的TypeScript入门指南
typescript
小崽崽17 小时前
如何实现React 19+Vite+TypeScript技术栈告别高薪主播!从零打造 24 小时“AI 销冠”:星云数字人直播间全链路实战
人工智能·react.js·typescript
wgc2k7 小时前
Nest.js基础-4:Nest.js,游戏服务器,微服务架构
游戏·typescript·node.js
wgc2k8 小时前
Nest.js基础-3:常用框架比较
typescript·node.js
blingverse8 小时前
致敬napi-rs,我用两个宏打通 TypeScript ↔ Rust:TSFFI.B 双向 FFI 框架
typescript
蜡台9 小时前
Vue2 使用 typescript 教程
前端·vue.js·typescript
abigale0310 小时前
LangChain 多轮对话记忆:基于 session_id 实现多会话隔离
typescript·langchain·uuid·session_id
GISHUB10 小时前
Express + TypeScript + ESM 后端服务搭建教程
javascript·typescript·express
OpenTiny社区1 天前
操作ArkTS页面跳转及路由相关心得
前端·typescript·web·opentiny
柠檬の夏季1 天前
TypeScript入门
typescript