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()
相关推荐
琹箐1 天前
Ant ASpin自定义 indicator 报错
前端·javascript·typescript
Sun_light1 天前
5 个理由告诉你为什么有了 JS 还要用 TypeScript
前端·typescript
鲸鱼14666570754192 天前
Screeps TypeScript 教程:使用 tsup 解决模块加载问题并实现自动化部署
typescript
张志鹏PHP全栈3 天前
TypeScript 第四天,TypeScript的编译选项(一)
前端·typescript
Toomey3 天前
别再用 Parameters 乱推断了!vue-i18n 封装 t 函数的正确姿势
typescript
郑板桥303 天前
ts学习1
学习·typescript
前端拿破轮3 天前
女朋友要和我分手?!!居然是因为交不出赎金信,不会用哈希表😭😭😭
算法·leetcode·typescript
知识分享小能手4 天前
Bootstrap 5学习教程,从入门到精通,Bootstrap 5 表单验证语法知识点及案例代码(34)
前端·javascript·学习·typescript·bootstrap·html·css3
张志鹏PHP全栈4 天前
TypeScript 第三天,TypeScript中的类型(二)
typescript
成遇4 天前
Eslint基础使用
javascript·typescript·es6