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:修饰的属性或者方法只能读不能写
  • 相关阅读:
    Windows-快速预览文件-QuickLook
    Chrome简洁高效管理下载项
    有Bug?你的代码神兽选对了吗
    保护视力-刻不容缓
    一次看懂 Https 证书认证
    Web前端助手-功能丰富的Chrome插件
    Chrome自动格式化Json输出
    网络爬虫
    彻底搞懂Cookie,Session,Token三者的区别
    Redis内存满了的解决办法
  • 原文地址:https://www.cnblogs.com/shixiaokeng/p/14395652.html
Copyright © 2011-2022 走看看