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:修饰的属性或者方法只能读不能写
  • 相关阅读:
    设计模式
    设计模式
    设计模式
    设计模式
    【Sublime】许可证 及 相关设置
    【Linux】跳过ubuntu grub2引导,使用Windows引导ubuntu
    【Linux】Windows 7下硬盘安装Ubuntu 14.10图文教程
    【ACM】连连看 hdu1175
    【算法】约瑟夫环 C++源代码
    【Java】配置JAVA的环境变量
  • 原文地址:https://www.cnblogs.com/shixiaokeng/p/14395652.html
Copyright © 2011-2022 走看看