1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】アクセス修飾子

Posted at

アクセス修飾子とは

アクセス修飾子を使用することでメンバのアクセス範囲を限定することができます。
アクセス修飾子にはpublic, private, protectedがあります。

アクセス修飾子 範囲
なし publicと同様
public どこからでもアクセス可能
private クラス内のみアクセス可能
protected クラス内とサブクラスからアクセス可能

public

class Person { 
  // publicは省略可
  public name: string
  public age: number
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  profile(): string {
    return `name: ${this.name}, age: ${this.age}`
  }
}

let tanaka = new Person("Tanaka", 32)
console.log(tanaka.profile())
// > name: Tanaka, age: 32
// public のため参照可能

private

class Person {
  public name: string
  // private に変更
  private age: number
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  profile(): string {
    return `name: ${this.name}, age: ${this.age}`
  }
}

let tanaka = new Person("Tanaka", 32)
console.log(tanaka.profile())
//  > name: Tanaka, age: 32
// Profile 内のため参照可能
console.log(tanaka.name)
// > Tanaka
// public のため参照可能
console.log(tanaka.age)
// > error TS2341: Property 'age' is private and only accessible within class 'Person'.
// Person 外のため参照不可

protected

class Person {
  public name: string
  // public に変更
  public age: number
  // protected を追加
  protected nationality: string
  constructor(name: string, age: number, nationality: string) {
    this.name = name
    this.age = age
    this.nationality = nationality
  }
  profile(): string {
    return `name: ${this.name}, age: ${this.age}`
  }
}

class Android extends Person {
  constructor(name: string, age: number, nationality: string) {
    super(name, age, nationality)
  }
  profile(): string {
    return `name: ${this.name}, age: ${this.age}, nationality: ${this.nationality}`
  }
}

let kato = new Android("kato", 24, "Japan")
console.log(kato.nationality)
// > error TS2445: Property 'nationality' is protected and only accessible within class 'Person' and its subclasses.
// Preson 内でも Android 内でもないため参照不可
console.log(kato.profile())
// > name: kato, age: 24, nationality: Japan
// Android 内のため参照可能
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?