最近碰到了这段代码:
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行,我们使用function
将mock.data
分配给mock.json
。我们不能简单地写mock.json
= mock.data
吗?它有什么不同?
P上。 S.我对它收到的数据类型一无所知。
答案 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.data
为an 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
的当前值。