zoukankan      html  css  js  c++  java
  • 7、类class

    typescritp对类的支持可谓是更加丰富 除了ES6 ES7 已经有的内容还添加了一些新的内容

    7.1、面向对象的基础术语

    • 类(class):定义了一切事物的抽象特点
    • 对象(Object):类的实例
    • 面向对象(oop)的三大特征:封装 继承 多态

    // 创建以一个类

    class Animal {

    // 定义构造函数

    constructor(name) {

    this.name = name

    }

    // 定义方法

    run() {

    return `${this.name} is running`

    }

    }

    const snake = new Animal('lily')

    console.log(snake.run())

     

    // 继承

    // 新定义的Dog继承了Animal

    class Dog extends Animal {

    bark() {

    return `${this.name} is barking`

    }

    }

    const xiaobao = new Dog('xiaobao')console.log(xiaobao.run())console.log(xiaobao.bark())

    // 多态
    class Cat extends Animal {
          // 创建静态属性 - 可直接调用
          static categories = ['mammal']
          cosntructor(name) {
                 super(name)  // super重写构造函数
                 console.log(this.name)
          }
          run() {
                 return 'Meow, ' + super.run()
          }
    }
    const maomao = new Cat('maomao')
    console.log(maomao.run())

     

    7.2、TypeScript 中的类

    • Public:修饰的属性或方法是共有的
    • Private:修饰的属性或方法是私有的

    // 创建以一个类

    class Animal {

    // 定义构造函数

    constructor(name) {

    this.name = name

    }

    // 定义方法

    // 使用Private修饰 外部不可访问

    private run() {

    return `${this.name} is running`

    }

    }

    const snake = new Animal('lily')

    // 此时snake.run() 会报错

    console.log(snake.run())

     

    // 继承

    class Dog extends Animal {

    bark() {

    return `${this.name} is barking`

    }

    }

    const xiaobao = new Dog('xiaobao')
    // 此时xiaobao.run() 也会报错
    console.log(xiaobao.run())
    console.log(xiaobao.bark())
    • Protected:修饰的属性或者方法是受保护的
    // 创建以一个类

    class Animal {

    // 定义构造函数

    constructor(name) {

    this.name = name

    }

    // 定义方法

    // 使用Protected修饰 外部不可访问 但是自己的子类可以访问

    protected run() {

    return `${this.name} is running`

    }

    }

    const snake = new Animal('lily')

    // 此时snake.run() 会报错

    console.log(snake.run())

     

    // 继承

    class Dog extends Animal {

    bark() {

    return `${this.name} is barking`

    }

    }

    const xiaobao = new Dog('xiaobao')
    // 此时xiaobao.run() 不会报错
    console.log(xiaobao.run())
    console.log(xiaobao.bark())
      • readonly:修饰的属性或者方法只能读不能写
  • 相关阅读:
    echarts圆套圆
    两个对象深度比较,借鉴,记录
    js异步加载的方式
    elementUI使用el-card高度自适应
    如何在页面上实现一个圆形的可点击区域
    清除浮动
    水平垂直居中的几种方式
    BFC原理
    正则表达式
    Vue项目中难点问题
  • 原文地址:https://www.cnblogs.com/shixiaokeng/p/14395652.html
Copyright © 2011-2022 走看看