ES2022 プライベート・フィールドについて

前提

専門書のコードをES2022仕様で書き直してみたところ、
constructor内のhtmlはthis.#htmlとして初期化しようとすると、
div要素が生成されませんでした。エラーが表示される訳ではないのですが、
この不具合がよく分かりません。どうしてなのでしょうか。
よろしくお願い致します。

「改訂新版jQuery本格入門_サンプルコード_P282_list6-42」より

実現したいこと

理由を知りたい。

発生している問題・エラーメッセージ

なし。

jQuery

// 改訂新版jQuery本格入門_サンプルコード_P282_list6-42 // ボタンとカウンタの値を表示する要素を持つカウンタウィジェット var CounterWidget = function(id, btnVal, initial, step) { // ウィジェットの初期値を設定 this.id = id || 'counter'; this.btnVal = btnVal || 'カウンタ'; this.count = !isNaN(initial) && Number(initial) || 0; this.step = !isNaN(step) && Number(step) || 1; // HTMLの生成 this.html = '<div id="' + id + '" class="counter-widget">' + '<input type="button" value="' + btnVal + '" />' + '<span></span>' + '</div>'; }; CounterWidget.prototype = { inc: function() { // カウンタの加算 this.count += this.step; }, set: function(tag) { // カウンタの値を表示 tag.text(this.count); // tagはウィジェット内の<span> }, click: function() { // ボタンクリック時のイベント処理 this.inc(); this.set(this.tag); }, appendTo: function(toElem) { // ウィジェットのHTML文書への追加 this.root = $(this.html).appendTo(toElem); $(this.root).on('click', 'input[type="button"]', $.proxy(this, 'click')); this.tag = this.root.find('span'); this.tag.promise().done($.proxy(this, 'set')); // カウンタの初期値を表示 return this; }, remove: function() { $(this.root).off('click', 'input[type="button"]'); $(this.root).remove(); } }; new CounterWidget('counter1', '増えるカウンタ').appendTo(document.body); new CounterWidget('counter2', '減るカウンタ', 0, -1).appendTo(document.body);

jQuery

// 編集後 // ボタンとカウンタの値を表示する要素を持つカウンタウィジェット class CounterWidget { #btnVal; #count; #html; #id; #initial; #step; constructor(id, btnVal, initial, step, count, html) { // ウィジェットの初期値を設定 this.#btnVal = btnVal || `カウンタ`; this.#count = !Number.isNaN(initial) && Number(initial) || 0; this.#id = id || 'counter'; this.#step = !Number.isNaN(step) && Number(step) || 1; // 問題の箇所 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ //this.#html = html とするとエラーにならないがdiv要素が生成されない this.html = html || // HTMLの生成 `<div id="${ id }" class="counter-widget"> <input type="button" value="${ btnVal }"> <span></span> </div>`; } // カウンタの加算 inc() { this.#count += this.#step; } // カウンタの値を表示。 tagはウィジェット内の<span> set(tag) { tag.text(this.#count); } // ボタンクリック時のイベント処理 click() { this.inc(); this.set(this.tag); } // ウィジェットのHTML文書への追加 appendTo(toElem) { this.root = $(this.html).appendTo(toElem); $(this.root).on('click', 'input[type="button"]', $.proxy(this, 'click')); this.tag = this.root.find('span'); this.tag .promise() .done($.proxy(this, 'set')); // カウンタの初期値を表示 return this; } remove() { $(this.root).off('click', 'input[type="button"]'); $(this.root).remove(); } } new CounterWidget('counter1', '増えるカウンタ').appendTo(document.body); new CounterWidget('counter2', '減るカウンタ', 0, -1).appendTo(document.body);

コメントを投稿

0 コメント