LoginSignup
0
0

More than 1 year has passed since last update.

【javascript】getter/setter/static

Posted at

getter/setter/static

  • ディスクリプターの中にはオプションでgetter/setter/staticを追加することができる。
  • オブジェクトを呼び出した時に、同時に異なる処理をしたい場合に使用する。

case1

  • Person1コンストラクタにdefinePropertyを使用して、nameプロパティを追加。
  • 第三引数にget, setを追加していく。

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

// インスタンス化されたp1を,definePropertyで追加されたname経由でbobを出力している。
//すなわち出力される値は  _name === name となる。
Object.defineProperty(Person1.prototype, 'name',{
    get: function(){
        return this._name;
    },
    set: function(val){
        this._name = val;
    }
})

const p1 = new Person1('Bob', 45)
console.log(p1.name) >>> Bob

nameが追加されている。
スクリーンショット 2021-11-19 17.29.27.png

case2

  • setは追加されたプロパティに値を上書きすることができる。

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', 45)

//上書きしている。
p1.name = "Tom"
console.log(p1.name) >>> Tom

case3

  • メソッドが呼ばれるときはgetterも同時に呼び出されるのでget内で異なる処理を追加することができる。
function Person1(name, age) {
    this._name = name;
    this._age = age;
}

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

const p1 = new Person1('Bob', 45)

p1.name = "Tom"
console.log(p1.name)

case3

ES6からはクラスでより簡潔に書ける。


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

    get name(){
        alert('hello')
        return this._name;
    }
    set name(val){
        this._name = val;
    }
}

const p2 = new Person2('hoge', 33)
console.log(p2.name) >>> hoge

static

  • クラス内で記述できる。
  • メソッドを追加
  • インスタンス化しなくても使える。
    • thisが使えない。

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

    get name(){
        alert('hello')
        return this._name;
    }
    set name(val){
        this._name = val;
    }
    static hello(){
        console.log('hello23')
    }
}

Person2.hello() >>> hello23

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