Privateクラスフィールドを使わないclass構文では意図した通り作動してくれますが、
クラスの変数をプライベート変数として設定しようとすると、上手く行きません。
エラーも出ないのでどこに不具合があるのかがよく分からないです。
「改訂新版jQuery本格入門_サンプルコード_P260より」 一部編集しています。
調べたサイト
MDN plus
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Classes/Private_class_fields
JavaScript Primer
https://jsprimer.net/basic/class/
HTML
1<div> 2 <input type="button" value="カウンタ"> 3 <span id="count"></span> 4</div>
jQuery
1$(function() { 2 3 // 問題なく作動する 4 // カウンターオブジェクト 5 function Counter(initial, step) { 6 this.count = !isNaN(initial) && Number(initial) || 0; // 初期値 7 this.step = !isNaN(step) && Number(step) || 1; // 増分 8 } 9 10 // thisはCounterインスタンスを表す 11 Counter.prototype = { 12 increment() { this.count += this.step } 13 }; 14 15 // カウンタの値を表示する処理(thisと引数tagは$.proxyにて設定) 16 function adapter(tag) { $(tag).text(this.count); } 17 18 // 表示に用いるCounter()インスタンス 19 const counter = new Counter(); 20 21 // ボタンのクリックでカウンタを増やせるようにする 22 // increment、setはカスタムイベント 23 $('input[type="button"]').on({ 24 25 increment : $.proxy(counter, 'increment'), // カウンタを増やす 26 set : $.proxy(adapter, counter, $('#count')), // カウンタの値を表示 27 28 // カスタムイベントの発火(thisはクリックされた要素) 29 click() { 30 $(this) 31 .trigger('increment') 32 .trigger('set') 33 } 34 }); 35 36 // カウンタの初期値を表示 37 adapter.call(counter, $('#count')); 38});
jQuery
1// カウンターオブジェクトをclass構文で書き換えた 2// 問題なく作動 3class Counter { 4 constructor(count, step) { 5 this.count = !isNaN(count) && Number(count) || 0; // 初期値 6 this.step = !isNaN(step) && Number(step) || 1; // 増分 7 } 8 9 // thisはCounterインスタンスを表す 10 increment() { this.count += this.step; } 11} 12// 以下は元のコードと同じ
jQuery
1// 作動せず。 2class Counter { 3 #count; 4 #step; 5 6 constructor(count, step) { 7 this.#count = count; 8 this.#step = step; 9 } 10 11 get count() { 12 return this.#count; 13 } 14 15 get step() { 16 return this.#step; 17 } 18 19 set count(newCount) { 20 this.#count = !isNaN(newCount) && Number(newCount) || 0; // 初期値 21 } 22 23 set step(newStep) { 24 this.#step = !isNaN(newStep) && Number(newStep) || 1; // 増分 25 } 26 27 // thisはCounterインスタンスを表す 28 increment() { this.count += this.step; } 29} 30// 以下は元のコードと同じ

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/11/08 14:21
2022/11/08 14:32 編集