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()
相关推荐
QQRRRRW21 小时前
Tailwind+VScode (Vite + React + TypeScript) 原理与实践
vscode·react.js·typescript
我叫张小白。1 天前
JavaScript现代语法梳理:ES6+核心特性详解
开发语言·javascript·typescript·es6
我叫张小白。1 天前
TypeScript泛型进阶:掌握类型系统的强大工具
前端·javascript·typescript
爱学习的程序媛1 天前
【Web前端】Angular核心知识点梳理
前端·javascript·typescript·angular.js
驳是2 天前
TS 项目升级 React 18 到 19 的一些事情
前端·react.js·typescript
O***p6042 天前
TypeScript类型守卫
前端·javascript·typescript
流影ng2 天前
【HarmonyOS】自定义节点能力
typescript·harmonyos
6***x5452 天前
TypeScript在全栈开发中的使用
前端·javascript·typescript
1***Q7842 天前
TypeScript类型兼容
前端·javascript·typescript
Y***K4342 天前
TypeScript模块解析
前端·javascript·typescript