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在它们被定义的地方关闭,而不是在调用它们时设置它。在您的情况下,它正在关闭thisat 全局范围。

如果您创建普通函数initpushValue通过对通过创建的对象的引用调用它们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 回答