用于将某事物指定为对象属性的函数?

时间:2018-06-02 06:23:21

标签: javascript async-await

最近碰到了这段代码:

const fetchMock = async (name, type="success") => {
  const response = await fetch(someUrl);
  let mock = await response.json();
  mock = mock[type];
  mock.json = () => mock.data;
  return mock;
}

我无法理解为什么在第5行,我们使用functionmock.data分配给mock.json。我们不能简单地写mock.json = mock.data吗?它有什么不同?

P上。 S.我对它收到的数据类型一无所知。

1 个答案:

答案 0 :(得分:2)

您的问题与异步JSON抓取内容无关。最后,mock只是一个具有data属性的对象。它还需要json属性,以产生data属性。

因此,简化的代码示例如下所示:

const mock = {
  data: {
    "someKey": "someValue"
  }
};

mock.json = () => mock.data;

假设mock.json只设置了一次,mock.data被突变或更新。然后,mock.json = mock.data仅在mock.dataan object that stays the same reference时才能正常工作。

const mock = {
  data: {
    "someKey": "someValue"
  }
};

mock.json = mock.data;
console.log(mock.json); // { "someKey": "someValue" }, as expected
// …
mock.data.someKey = "someOtherValue"
console.log(mock.json); // { "someKey": "someOtherValue" }, as expected

// Either of these reassignments will break up the connection between `mock.json` and `mock.data`:
mock.data = {"newKey": "something"};
mock.data = "Something else";

console.log(mock.json); // { "someKey": "someOtherValue" }, no longer updated

这对mock.json = () => mock.data无关紧要,因为该函数只返回mock.data当前值。