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()
相关推荐
濮水大叔9 小时前
不必把 Vue3 写成“麻花”:从状态碎片到对象协作,重新理解 Zova 的前端心智模型
前端·typescript·vue3·ioc·tsx·zova
退休倒计时13 小时前
【每日一题】LeetCode 45. 跳跃游戏 II TypeScript
算法·leetcode·typescript
TunerT_TQ15 小时前
GitHub深度工程评测:Cline 源码级工程评测|65k Star 开源AI编程助手的工程全景
typescript·开源·github·vs code·ai编程助手·开源供应链安全·静态源码审计
贩卖黄昏的熊1 天前
NestJS简明教程——安全
开发语言·javascript·安全·typescript·nest.js
theoweb31 天前
Typescript关于sort需要注意的地方
typescript
黄泉路醉s1 天前
在Vant+Vue+TypeScript的H移动前端使用UnoCSS
前端·vue.js·typescript
不好听6132 天前
TypeScript 类型系统:`type` vs `interface` 与 `import type`
typescript
晓说前端2 天前
TypeScript 高级特性 —— 类型断言与泛型
前端·typescript
烬羽3 天前
React 状态提升:一个 ColorPicker,彻底搞懂状态该放哪里
react.js·typescript·设计
ji_shuke3 天前
Playwright 从零到 CI 实战:基于 TypeScript 的端到端测试完整指南
javascript·ci/cd·typescript·playwright