Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active June 25, 2022 03:12
Show Gist options
  • Save yano3nora/6c726cd14c33e0f6841516a1503f38cc to your computer and use it in GitHub Desktop.
Save yano3nora/6c726cd14c33e0f6841516a1503f38cc to your computer and use it in GitHub Desktop.
[js: get / set] Object Accessor (Getter/Setter). #js

Overview

get ゲッター - developer.mozilla.org
set セッター - developer.mozilla.org
プロパティ getters と setters
【JavaScript】Self Objectの値を参照してプロパティ値設定したい

普通の言語でよくある getter, setter を object に生やせる。caniuse 見るに結構いにしえの構文っぽいけど知らんかった ... 多分 IE が NG だったからかな。

Get

const user = {
  name: 'John',
  surname: 'Smith',

  get fullName () {
    return `${this.name} ${this.surname}`
  },
}

console.log(user.fullName) // John Smith

Set

const user = {
  _name: 'John', // 別に隠匿しなくてもいいけど、したほうが良さげ

  get name () {
    return this._name
  },

  set name (value) {
    this._name = value
  },
}

// get name() で最初は John
console.log(user.name) // John

// set name('Alice') みたいなことになっとる
user.name = 'Alice'

console.log(user.name) // Alice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment