0
如何定義類級別常量並在靜態&實例方法中訪問它?如何在ES6類中定義類級別常量
class ExternalRequests{
const HEADERS = { "Accept": "application/json, text/plain", "Content-Type": "application/json", "Access-Control-Allow-Origin": "*"}
static get(url){
return fetch(url, {method: 'get', HEADERS})
.catch(_ => {
throw new Error("network error");
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
});
}
static post(url, data){
return fetch(url, {method: 'post', HEADERS, body: data})
.catch(_ => {
throw new Error("network error");
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
});
}
static put(url, data){
return fetch(url, {method: 'put', HEADERS, body: data})
.catch(_ => {
throw new Error("network error");
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
});
}
static delete(){
return fetch(url, {method: 'delete', HEADERS})
.catch(_ => {
throw new Error("network error");
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
});
}
}
export default ExternalRequests;
錯誤
ERROR in ./externalRequests.js
Module build failed: SyntaxError: Unexpected token (3:8)
1 | class ExternalRequests{
2 |
> 3 | const HEADERS = { "Accept": "application/json, text/plain", "Content-Type": "application/json", "Access-Control-Allow-Origin": "*"}
如果你班上的每種方法都是'靜態',那麼你不想要或不需要一個類,你只需要一個對象。如果你只是導出一個默認對象,你實際需要的是一堆命名導出。 – loganfsmyth