0
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 3 years have passed since last update.

Class構文

Posted at

目的

通常のJSで書いた場合とClass構文で書いた場合の比較

サンプル

HTML

<p class="js-button" data-button-id="1">button</p>
<p class="js-button" data-button-id="2">button</p>

通常のJS

const button = document.querySelectorAll('.js-button')
for (const el of button) {
  el.addEventListener('click', e => {
    const number = e.currentTarget.getAttribute('data-button-id')
    console.log(number)
  })
}

Class構文を利用

class Button {
  constructor(el) { // 変数を定義
    this.el = el
  }
  init() { // 動作を定義
    this.el.addEventListener('click', e => {
      const number = e.currentTarget.getAttribute('data-button-id')
      console.log(number)
    })
  }
}
const buttons = document.querySelectorAll('.js-button')
for (const button of buttons) {
  new Button(button).init()
}

結論

簡単な動作の場合はClass構文で書くと記述が増えたように感じてしまう
しかし、変数と関数が見やすくなっているので、挙動が複雑なJSを書いているときにとても便利でした

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?