# getter(computed property)

# Ruby

attr_reader :name
# このようにアクセスしたい
c = Class01.new
c.member01 = 'Hello'
puts c.member01 # => 'Hello'

# そのとき、

# このように書くのと
class Class01
    attr_accessor :member01
end

# このように書くのは同じ意味
class Class01
    def member01 # getter
        @member01
    end

    def member01=(val) # setter
        @member01 = val
    end
end

# これも一緒
class Class01
    attr_reader :member01
    attr_writer :member01
end

# Swift

var name: String { get { return this.mName } }

# TypeScript

get name(): string { return this.mName; }
class Class01 {
    private mName: string;
    private mAge: number;

    constructor(name: string, age: number) {
        this.mName = name;
        this.mAge = age;
    }

    get name(): string { return this.mName; }
    set name(v: string) { this.mName = v; }
    get age(): number { return this.mAge; }
    set age(v: number) { this.mAge = v; }
}

const c = new Class01("testarou", 15);
c.name      // => "testarou"
c.age       // => 15
c.age++     // => 16
c.age += 2  // => 18
c.age = 20  // => 20
  • name, name, age, age の順で書くのが良いらしい
  • name, age, name, age の順で書くと、TSLint に怒られる

All 'name' signatures should be adjacent (adjacent-overload-signatures)

[ 📩 ご意見 ]