【问题标题】:When using Object.create() how do you reference Object keys withing other object keys使用 Object.create() 时,如何使用其他对象键引用对象键
【发布时间】:2016-11-27 18:13:48
【问题描述】:

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

问题:

如何在元素的另一个属性中引用对象的属性,就像使用类一样。 或者我的示例不是一个很好的模式?如果是这样,我应该如何构建我的计算器对象以提供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>

【问题讨论】:

    标签: javascript event-handling object-create


    【解决方案1】:

    该代码中的问题是您使用了箭头函数,但关闭了错误的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');
    

    您确实需要从事件侦听器bindpushValue 的调用(否则,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>

    【讨论】:

    • 啊,这么简单。该死的肥箭陷阱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多