我正在尝试在 JavaScript 中扩展 Request 对象。我的用例是我想包含更多方法并根据 httpMethod
修改 URL。
我试过如下:
class ServiceRequest extends Request {
constructor(config) {
const url = config && config.url;
const method = config && config.method;
const body = config && (JSON.stringify(config.body) || {});
const headers = (config && config.headers) || new Headers({
'Content-Type': 'application/json; charset=UTF-8',
Accept: 'application/json',
});
if (url && method) {
const apiUrl = this.buildAPIPath(url, method);
}
super(apiUrl, {method,body,headers});
}
buildAPIPath (url, httpmethod) {// all the url modifications return modify url;}
}
现在它在没有 super 的情况下出错,我不能调用它。我的问题是 url 是只读的,所以我不能先调用 super。如果我先调用 super 然后我不能重新分配 url。
关于如何让它发挥作用的一些建议?
最佳答案
I am trying to extend
Request
object in JavaScript.
绝对没有理由这样做——您不会覆盖它的任何方法。只需编写一个返回普通 Request
的普通函数:
function buildAPIPath (url, httpmethod) {
// all the url modifications
return /* modified url */;
}
export function ServiceRequest(config) {
const url = config && config.url;
const method = config && config.method;
const body = config && JSON.stringify(config.body || {});
const headers = (config && config.headers) || new Headers({
'Content-Type': 'application/json; charset=UTF-8',
Accept: 'application/json',
});
const apiUrl = buildAPIPath(url, method);
return new Request(apiUrl, {method,body,headers});
}
It is giving error I can not call this class function before calling super
是的。在 super
调用之前,不存在任何实例,因此您不能对其调用任何方法。真的没有办法解决这个问题。但是您的 buildAPIPath
方法并不使用 实例,因此它根本不应该是一个方法。您可以在 class
之外使用普通函数声明,或静态方法(您可以使用 new.target.buildAPIPath(...)
或 ServiceRequest 调用。 buildAPIPath(…)
).
关于javascript - 在javascript类中调用super之前先调用类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49108069/