0
私のプロジェクトでは、実際のクラスを実装することで、改善したいと思っています。JSクラスを実クラスに変換する
const Fetch = {};
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
const error = new Error(response.statusText);
error.response = response;
throw error;
}
}
function parseJSON(response) {
return response.json();
}
/**
* @function
* @name Fetch
*/
Fetch.Fetch = (src, options = {}) => {
return window.fetch(src, options)
.then(checkStatus);
}
/**
* @function
* @name FetchJSON
*/
Fetch.FetchJSON = (src, options = {}) => {
return window.fetch(src, options)
.then(checkStatus)
.then(parseJSON);
}
/**
* @function
* @name GetJSON
*/
Fetch.GetJSON = (src, options = {}) => {
options = Object.assign({}, options, {
method: 'GET'
});
return Fetch.FetchJSON(src, options);
}
Fetch.GetApiJSON = (src, options = {}) => {
options = Object.assign({}, options, {
headers: {
'some-info': 'your header'
}
});
return Fetch.GetJSON(src, options);
}
module.exports = Fetch;
私はクラスを作成する方法ではないことを知っています。私はそのように変換したいと思います。しかし、私はこれらのヘルパーのために少し混乱しています。
あなたがそのような何かを持っをどう思いますか:
new Fetch(url, options).Fetch();
new Fetch(url, options).GetJSON();
私は、そのように約束を使用することができます。 簡単に言えば、それが最善の方法だと思いますか?
今、あなたは、オブジェクトに添付メソッドの束を持っています。あなたが何かの複数のインスタンスを望んでいない/必要としないなら、そうすることは完全に容認できる方法です。複数のインスタンスを作成できるようにするには、コンストラクタを作成する必要があります。 –