私は工夫された電卓モジュールを作ることによって Object.create を学ぼうとしています。試しbind
てみました を削除しようとしましthis
たが、結果はありません。
質問:
クラスの場合のように、要素の別のプロパティ内でオブジェクトのプロパティをどのように参照しますか。それとも、私の例はあまり良いパターンではありませんか? もしそうなら、イベントリスナーを提供するために電卓オブジェクトをどのように構築すればよいcreation
ですか?
電卓.js
const Calculator = {
inputArr: [],
init: (selector)=> {
const el = document.querySelector(selector);
el.addEventListener('click', this.pushValue); // this wont work.
return this;
},
pushValue: (e) => {
let val = e.target.value;
if(val){
this.inputArr.push(val);
console.log(e.target, this.inputArr); // this wouldn't work.
}
}
};
const adder = Object.create(Calculator).init('#calc');
HTML:
<div id="calc">
<button class="btns" value="1">1</button>
<button class="btns" value="2">2</button>
</div>