LoginSignup
1
1

More than 3 years have passed since last update.

【JS学習その⑩】JavaScriptにおけるgetter/setterとstatic

Posted at

JS学習シリーズの目的

このシリーズは、私ジャックが学んだJavaScriptのメカニズムについてアウトプットも兼ねて、
皆さんと知識や理解を共有するためのものです。
(理解に間違いがあればご指摘いただけると幸いです)

getter/setterとは

  • getter => 「プロパティが参照された際に行う処理
  • setter => 「プロパティに変更があった際に行う処理

プロパティにはディスクリプターというものがあり、その中にgetとsetがある

main.js
function Person1(name, age) {
    this._name = name;
    this._age = age;
}

Object.defineProperty(Person1.prototype, 'name', {
    get: function() {
        return this._name;
    },
    set: function(val) {
        this._name = val;
    }
)};

const p1 = new Person1('Bob', 23);

console.log(p1.name); /*Bob*/

p1.name = 'Tom';
console.log(p1.name); /*Tom*/

上記のコードでは、
Object.definePropertyメソッドでPerson1.prototype内のnameプロパティのディスクリプターを直接定義しています。
上記のgetがgetter,setがsetterです。

また、ES6からは上記をクラス構文で次のように簡略化して記述できます。

main.js
class Person2 {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }

    get name() {
        return this._name;
    }

    set name(val) {
        this._name = val;
    }
}

const p2 = new Person2('Bob', 23);
console.log(p2.name); /*Bob*/

p2.name = 'Tom';
console.log(p2.name); /*Tom*/

静的メソッドとは

インスタンス化せずに直接実行できるメソッド
静的メソッドはクラス内でstaticというキーワードを使用して定義します。

main.js
class Person2 {
    constructor(name, age) {
        this._name = name;
        this._age = age;
    }

    get name() {
        return this._name;
    }

    set name(val) {
        this._name = val;
    }

    static hello() {
        console.log('hello');
    }
}

Person2.hello() /*hello*/

上記のhelloメソッドが静的メソッドになります。
前述したように、静的メソッドはインスタンス化せずに直接実行できます。ただ、注意点があります。
それは、静的メソッド内(static内)ではthisは使えないということです。

また、静的メソッドは他のメソッドと違い、__prototype__内に定義されるのではなくconstructor内に生成されます
だからインスタンス化しなくても直接実行できるという訳です。

main.js
function Person1(name, age) {
    this._name = name;
    this._age = age;
}

Person1.hello = function() {
    console.log('hello');
}

Person1.hello(); /*hello*/

よってクラス内でstaticを使って定義した静的メソッドは上記のようにして書いたものと同じということです。

まとめ

いかがでしたでしょうか。
getter,setterとstatic(静的メソッド)はJavaScriptにおいて重要なのでしっかり理解しておきましょう!

1
1
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
1