使用 Object.create() 时如何在另一个对象键中引用对象键

When using Object.create() how do you reference Object keys withing other object keys

我正在尝试通过制作一个人为设计的计算器模块来学习 Object.create。我试过 bind 我试过删除 this,但没有结果。

问题:

如何像使用 class. 一样在元素的另一个 属性 中引用一个对象的 属性 或我的例子不是一个很好的模式吗?如果是这样,我应该如何 构造我的计算器对象以在 creation 上提供事件侦听器?

Calculator.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>

该代码中的问题是您使用了箭头函数,但关闭错误 this。箭头函数关闭它们定义的 this ,而不是在它们被调用时设置它。在您的情况下,它在全球范围内关闭 this

如果您创建 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 从事件侦听器调用 pushValue(否则,this 将引用该元素)。或者,将其包裹在箭头中:

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>