我们如何定义类级别常量并在静态&中访问它实例方法?
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": "*"}
答案 0 :(得分:0)
将其更改为static get
访问者。然后,您可以从其他静态方法以this.HEADERS
的形式访问它。 (不幸的是,这是我们获得的最好的,直到JS获得类属性)
class ExternalRequests{
static get HEADERS() {
return {
"Accept": "application/json, text/plain",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
}
static get(url){
return fetch(url, {method: 'get', this.HEADERS})
}
/* rest of the class ... */
如果您现在要使用类属性,可以使用babel-transform-class-properties
,这样您就可以:
class ExternalRequests {
static HEADERS = /* ... your headers */
/* ...rest of the class... */