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()
相关推荐
Dragon Wu3 小时前
Electron Forge集成React Typescript完整步骤
前端·javascript·react.js·typescript·electron·reactjs
We་ct18 小时前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
程序猿阿伟1 天前
《TypeScript中Protobuf到运行时类型安全的转换指南》
javascript·安全·typescript
We་ct1 天前
LeetCode 228. 汇总区间:解题思路+代码详解
前端·算法·leetcode·typescript
阿蒙Amon2 天前
TypeScript学习-第10章:模块与命名空间
学习·ubuntu·typescript
VT.馒头2 天前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
AAA阿giao2 天前
从零拆解一个 React + TypeScript 的 TodoList:模块化、数据流与工程实践
前端·react.js·ui·typescript·前端框架
hedley(●'◡'●)2 天前
基于cesium和vue的大疆司空模仿程序
前端·javascript·vue.js·python·typescript·无人机
百锦再2 天前
Vue高阶知识:利用 defineModel 特性开发搜索组件组合
前端·vue.js·学习·flutter·typescript·前端框架
小杨同学呀呀呀呀2 天前
Ant Design Vue <a-timeline>时间轴组件失效解决方案
前端·javascript·vue.js·typescript·anti-design-vue