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()
相关推荐
能来帮帮蒟蒻吗4 天前
VUE3 -综合实践(Mock+Axios+ElementPlus)
前端·javascript·vue.js·笔记·学习·ajax·typescript
菜鸟una4 天前
【taro3 + vue3 + webpack4】在微信小程序中的请求封装及使用
前端·vue.js·微信小程序·小程序·typescript·taro
struggle20255 天前
continue通过我们的开源 IDE 扩展和模型、规则、提示、文档和其他构建块中心,创建、共享和使用自定义 AI 代码助手
javascript·ide·python·typescript·开源
Bl_a_ck5 天前
【React】Craco 简介
开发语言·前端·react.js·typescript·前端框架
Bl_a_ck5 天前
开发环境(Development Environment)
开发语言·前端·javascript·typescript·ecmascript
菜鸟una6 天前
【layout组件 与 路由镶嵌】vue3 后台管理系统
前端·vue.js·elementui·typescript
浪裡遊7 天前
Typescript中的对象类型
开发语言·前端·javascript·vue.js·typescript·ecmascript
从味书7 天前
安装typescript时,npm install -g typescript报错
javascript·typescript·npm
風吹过8 天前
A* (AStar) 寻路
typescript·cocos2d
geovindu9 天前
vue3: pdf.js 2.16.105 using typescript
javascript·vue.js·typescript·pdf