実現したいこと
this
を使用する意義と使用方法について理解を深めたいです。
前提
javascriptでスロットマシンの作成に挑戦しており、
その過程でクラスについて学習しています。
お手本のコードは以下です。
js
1'use strict'; 2 3{ 4 class Panel { //クラス 5 constructor() { //コンストラクタ 6 const section = document.createElement('section'); 7 section.classList.add('panel'); 8 9 this.img = document.createElement('img'); 10 this.img.src = this.getRandomImage(); 11 12 this.timeoutId = undefined; 13 14 this.stop = document.createElement('div'); 15 this.stop.textContent = 'STOP'; 16 this.stop.classList.add('stop'); 17 this.stop.addEventListener('click', () => { 18 clearTimeout(this.timeoutId); 19 }); 20 21 section.appendChild(this.img); 22 section.appendChild(this.stop); 23 24 const main = document.querySelector('main'); 25 main.appendChild(section); 26 } 27 28 getRandomImage() { 29 const images = [ 30 'img/seven.png', 31 'img/bell.png', 32 'img/cherry.png', 33 ]; 34 return images[Math.floor(Math.random() * images.length)]; 35 } 36 37 spin() { 38 this.img.src = this.getRandomImage(); 39 this.timeoutId = setTimeout(() => { 40 this.spin(); 41 }, 50); 42 } 43 } 44 45 const panels = [ //インスタンス 46 new Panel(), 47 new Panel(), 48 new Panel(), 49 ]; 50 51 const spin = document.getElementById('spin'); 52 spin.addEventListener('click', () => { 53 panels.forEach(panel => { 54 panel.spin(); 55 }); 56 }); 57}
質問内容
6行目~14行目にかけてthis
が多用されていますが、
これが何を意味するものか理解できません。
クラスから生成されるインスタンスを
this
で表示する
検索結果、上記の情報を得られましたが、
this
とインスタンスの関連性が分からず混乱しています。
現状を踏まえ、以下3点についてお伺いしたいです。
1. this
とは一体何者なのか
2. this
はどのタイミングで使用されるのか
3. img
stop
には付与されるのに、main
やsection
にはなぜ付与されないのか
試してみたこと
this
の定義及び使用例について検索しました。
併せて、クラス
コンストラクタ
インスタンス
についても検索しました。
一通り言葉の意味を理解することはできましたが、
まだ点として理解している感覚です。
各用語がどのように紐づいてクラスを成すのか、
こちらの質問を通じて理解したいです。

回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2022/10/05 10:19
2022/10/05 11:43 編集
2022/10/05 15:37