欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

TypeScript 類class與修飾符的詳細(xì)使用教程

 更新時間:2022年06月15日 15:36:46   作者:卡爾特斯  
通過 class 關(guān)鍵字定義一個類,然后通過 new 關(guān)鍵字可以方便的生產(chǎn)一個類的實(shí)例對象,這個生產(chǎn)對象的過程叫 實(shí)例化,類的成員就是類中所有的屬性和方法,這篇文章主要介紹了TypeScript 類class與修飾符的詳細(xì)使用,需要的朋友可以參考下

一、簡介

通過 class 關(guān)鍵字定義一個類,然后通過 new 關(guān)鍵字可以方便的生產(chǎn)一個類的實(shí)例對象,這個生產(chǎn)對象的過程叫 實(shí)例化,類的成員就是類中所有的屬性和方法。

// 定義類
class Person {
  // 名稱
  name: string
  // 年齡
  age: number
  // 構(gòu)造函數(shù)
  constructor(name: string, age: number) {
    // 更新熟悉數(shù)據(jù)
    this.name = name
    this.age = age
  }
}
// 發(fā)送一個人的信息
function sendPerson (person: Person) {
  console.log(`姓名:${person.name},年齡:${person.age}`)
}
// 實(shí)例化對象
const p = new Person('dzm', 20)
sendPerson(p) // 名稱:dzm,年齡:20

實(shí)例在new出來的時候,它實(shí)際是調(diào)用了類中的一個方法進(jìn)行初始化,這個方法被叫做構(gòu)造器,一般都會在類中顯示地寫上 constructor 方法,如果沒有顯示定義的 constructor,就會調(diào)用系統(tǒng)自帶的 constructor 構(gòu)造函數(shù)。

二、成員修飾符

訪問修飾符的作用就是用于限制別人亂用類中的東西

訪問修飾符

  • public:公開的,誰都能用(默認(rèn)就是 public
  • private:私有的,僅類自己能使用,子類與外部都不能使用
  • protected:受保護(hù)的,僅類和類的子類能使用,外部不能使用
// 定義類
class Person {
  // 公開參數(shù)
  name: string
  // 公開參數(shù)
  public age: number
  // 私有參數(shù)
  private num:number = 10
  // 內(nèi)部參數(shù)
  protected num1: number = 20
  // 構(gòu)造函數(shù)
  constructor(name: string, age: number) {
    // 更新熟悉數(shù)據(jù)
    this.name = name
    this.age = age
  }
  // 發(fā)送個人信息
  public send() {
    console.log('發(fā)送成功1')
  }
  // 私有方法
  private post() {
    console.log('發(fā)送成功2')
  }
}

只讀修飾符

readonly:只能讀不能寫

class Person {
  // 聲明賦值
  readonly name = 'dzm'
}
let p = new Person()
console.log(p.name)
// 不能賦值
// p.name = 'xxx'

readonly 只能在 constructor 構(gòu)造方法初始化時賦值,或者聲明時賦值,之后都不能在修改值。

class Person{
  readonly name: string
  // 構(gòu)造初始化賦值
  constructor(name: string) {
    this.name =  name
  }
}

靜態(tài)修飾符

static:靜態(tài)成員無需實(shí)例化,直接通過類名調(diào)用

// 定義類
class Person {
  // 公開參數(shù)
  name: string
  // 公開參數(shù)
  public age: number
  // 靜態(tài)參數(shù)
  static num:number = 10
  // 構(gòu)造函數(shù)
  constructor(name: string, age: number) {
    // 更新熟悉數(shù)據(jù)
    this.name = name
    this.age = age
  }
  // 發(fā)送個人信息
  static send() {
    console.log('發(fā)送成功')
  }
}
// 不需要實(shí)例化對象,通過類名就能進(jìn)行訪問
console.log(Person.num)
Person.send()

總結(jié)

1、上面總共分為三種類型修飾符:訪問修飾符、只讀修飾符、靜態(tài)修飾符

2、修飾符是可選的,在沒有寫任何修飾符的情況下,默認(rèn)為 public。

3、同類型修飾符只能有一個,也就是上面 三種修飾符 可以組合起來修飾一個成員。

4、三種類型修飾符有先后順序,分別是:訪問、靜態(tài)、只讀,即:public/static/protected、static、readonly

到此這篇關(guān)于TypeScript 類class與修飾符的詳細(xì)使用的文章就介紹到這了,更多相關(guān)TypeScript 類class內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論