0

私は工夫された電卓モジュールを作ることによって 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>
4

1 に答える 1

3

そのコードの問題は、アロー関数を使用したが、間違った を閉じていることthisです。アロー関数thisは、呼び出されたときに設定されるのではなく、定義された場所を閉じます。あなたの場合、thisグローバルスコープで閉じています。

通常の関数を作成initし、 でpushValue作成されたオブジェクトへの参照を介してそれらを呼び出すObject.createと、正しい で呼び出されますthis

const Calculator = {
  inputArr: [],
  init: function(selector) {                                 // ****
    const el = document.querySelector(selector);
    el.addEventListener('click', this.pushValue.bind(this)); // ****
    return this;
  },
  pushValue: function(e) {                                   // ****
    let val = e.target.value;
    if(val){
      this.inputArr.push(val);
      console.log(e.target, this.inputArr);
    }
  }
};

const adder = Object.create(Calculator).init('#calc');

イベントリスナーから をbind呼び出す必要があります (そうしないと、要素が参照されます)。または、矢印で囲みます。pushValuethis

el.addEventListener('click', e => this.pushValue(e));

で矢印ラッパーを使用した作業例this.pushValue:

const Calculator = {
  inputArr: [],
  init: function(selector) { // ****
    const el = document.querySelector(selector);
    el.addEventListener('click', e => this.pushValue(e)); // ****
    return this;
  },
  pushValue: function(e) { // ****
    let val = e.target.value;
    if (val) {
      this.inputArr.push(val);
      console.log(e.target, this.inputArr);
    }
  }
};

const adder = Object.create(Calculator).init('#calc');
<div id="calc">
  <button class="btns" value="1">1</button>
  <button class="btns" value="2">2</button>
</div>

于 2016-11-27T18:17:39.163 に答える