functionとprototypeで記述された関数をclassを使って書き換えてみました。
ES2015の書き方では問題なく作動しましたが、 ES2022のプライベートのフィールドを
設定した所、作動してくれなくなりました。エラーメッセージはありません。
どうしてなのか原因が分かりません。教えて頂けないでしょうか。よろしくお願い致します。
「改訂新版jQuery本格入門 P290リスト6-51」より。コードは私が編集を加えました。
jQuery
1 const Counter = function(initial, step) { 2 this.count = !Number.isNaN(initial) && Number(initial) || 0; // 初期値 3 this.step = !Number.isNaN(step) && Number(step) || 1; // 増分 4 }; 5 6 Counter.prototype = { // thisはCounterインスタンスを表す 7 inc() { this.count += this.step; } 8 }; 9 10 const LimitCounter = function(counter, limit) { 11 this.counter = counter; 12 this.count = this.counter.count; 13 this.deferred = $.Deferred(); // resolve実行のためのDeferredオブジェクト 14 this.limit = limit; 15 // このオブジェクトにPromiseの機能を追加。($.whenや.promise()を記述しなくて済む) 16 this.deferred.promise(this); 17 }; 18 19 LimitCounter.prototype = { 20 inc() { 21 if (!this.deferred.state() !== 'resolved') { 22 this.counter.inc(); 23 this.count = this.counter.count; 24 25 if (this.counter.step > 0 && this.counter.count >= this.limit || 26 this.counter.step < 0 && this.counter.count <= this.limit) { 27 28 // 限度に達したらresolveを実行 29 this.deferred.resolve(this.limit, this.count); 30 } 31 } 32 } 33 }; 34 35 const counter = new LimitCounter(new Counter(1, 2), 4); 36 37 // カウンタの値が限度に達したらdoneで登録された処理を実行 38 counter.done(function(limit, count) { 39 alert(`カウンタの値が${ limit }に達しました(${ count })`); 40 }); 41 42 // カウンタの値を表示する処理(thisと引数は$.proxyにて設定) 43 const adapter = function(tag) { $(tag).text(this.count); }; 44 45 // ボタンのクリックでカウンタを増やせるようにする 46 $(':button').bind({ // inc, setはカスタムイベント 47 inc : $.proxy(counter, 'inc'), // カウンタを増やす 48 set : $.proxy(adapter, counter, $('#count')), // カウンタの値を表示 49 click() { // カスタムイベントの発火(thisはクリックされた要素) 50 $(this) 51 .trigger('inc') 52 .trigger('set'); 53 } 54 }); 55 56 // カウンタの初期値を表示 57 adapter.call(counter, $('#count'));
jQuery
1 class Counter { // ES2015 作動する。他の部分は変更していない。 2 constructor(initial, step) { 3 this.count = !Number.isNaN(initial) && Number(initial) || 0; // 初期値 4 this.step = !Number.isNaN(step) && Number(step) || 1; // 増分 5 } 6 7 inc() { this.count += this.step; } // thisはCounterインスタンスを表す 8 }
jQuery
1class Counter { // ES2022 作動せず。 2 #count; 3 #step; 4 5 constructor(initial, step) { 6 this.#count = !Number.isNaN(initial) && Number(initial) || 0; // 初期値 7 this.#step = !Number.isNaN(step) && Number(step) || 1; // 増分 8 } 9 10 inc() { this.#count += this.#step; } // thisはCounterインスタンスを表す 11}
回答2件