繁体   English   中英

JavaScript:创建使用具有特定属性的方法返回对象的工厂函数

[英]JavaScript: Create Factory Function that Returns Object with Methods That Have Specific Properties

我有一个返回对象的工厂函数。 在对象中,我有一个名为 getNext 的方法。

我希望getNext方法返回一个具有属性valuedone的对象。

下面是我的代码,但似乎我在返回括号中的内容不正确。

function makeIterator (arr){

  let methodCalls = 0; 

    return {
      getNext(obj){
        methodCalls += 1; 

        return {
          this.value = ''; 
          this.done = ''; 
        }
      },

      getIndex(){
        return methodCalls
      }
    }
  }

我上面的代码没有通过下面的测试规范:

it('the `getNext` method returns an object with the properties `value` and `done`', () => {
    const iterator = makeIterator(['first', 'second', 'third']);
    const iterableInfo = iterator.getNext();

expect(Object.keys(iterableInfo).sort()).toEqual(['done', 'value'].sort());
    expect(iterableInfo.hasOwnProperty('value')).toBe(true);
    expect(iterableInfo.hasOwnProperty('done')).toBe(true);
  });

我究竟做错了什么?

似乎您正在尝试使用destructuring assignment

下面是一个示例:

var a, b, rest;
[a, b] = [10, 20];

更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM