在重构Bug报告代码时,我将一个函数移动到一个新的类'Logger'中,并调用静态方法,如下所示:
$("#bugForm").submit((e) => {
e.preventDefault()
const input = document.getElementById('nameInput');
bugInfo = {
"name": `[${ticket.id}] Bug report`,
"story_type" : "Bug",
"description": `+ ${urlHelper.zendeskTicketUrl}` + " n" + `+ ${input.value}`,
}
Logger.logInfo(bugInfo).then(collapse.collapse('toggle'))
})
});
但是当我运行静态方法时,我收到以下错误:
Uncaught (in promise) ReferenceError: metadata is not defined
Logger.js
class Logger {
constructor(settings) {
this.settings = settings;
}
static async logInfo(data = {}) {
console.log('Hello!')
const url = 'exampleUrl'
const response = fetch(url, {
method: 'POST',
headers: {
"Token": `${metadata.settings.token}`,
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
return response.json();
}
}
为了解决这个问题,我在代码中添加了以下行:
const logger = new Logger(metadata.settings);
并收到以下错误:
Uncaught (in promise) ReferenceError: Cannot access 'Logger' before initialization
我最初只使类使用它的静态方法,需要元数据阻止我这样做吗?我用错了吗?
问题在于你传递元数据。设置的方式
我已经改变了你使用设置的方式。下面是一个工作代码片段
$("#bugForm").submit((e) => {
e.preventDefault()
const input = document.getElementById('nameInput');
// logic here
const bugInfo = {
info: "Hello"
}
// changed here as I removed static
logger.logInfo(bugInfo).then(console.log('print'))
});
class Logger {
constructor(settings) {
// getting the settings here and assigning it to the constructor variable
this.settings = settings;
console.log('hello', this.settings)
}
// removed static
async logInfo(data = {}) {
console.log('Hello!')
const url = 'exampleUrl'
console.log(data);
console.log(this.settings)
const response = fetch(url, {
method: 'POST',
headers: {
// using it here while calling the method
"Token": `${this.settings.token}`,
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
return response.json();
}
}
const metadata = {
settings: {
token: 'hello'
}
}
const logger = new Logger(metadata.settings);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="bugForm">
<button type="submit">
Submit
</button>
</form>