【问题标题】:JavaScript: Create Factory Function that Returns Object with Methods That Have Specific PropertiesJavaScript:使用具有特定属性的方法创建返回对象的工厂函数
【发布时间】:2019-10-18 09:27:58
【问题描述】:

我有一个返回对象的工厂函数。在对象中,我有一个名为 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);
  });

我做错了什么?

【问题讨论】:

  • 严格回答你的问题,返回 {value:'', done:''} 作为标准对象初始化

标签: javascript object methods properties return


【解决方案1】:

您似乎正在尝试使用destructuring assignment

下面是一个示例:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2015-10-21
    相关资源
    最近更新 更多