I’m new to node.js I’ve been coding some node.js based application, and met a behavior that I can’t understand. Bellow is and example code, in the main function, it initializes the class then uses it to map into another object. When I declare this mapper’s value to an arrow function, it successfully catches the local variable main
. But when I don’t declare the value as an arrow function, it throws an error like this.
this.env.url + "/messages",
^
TypeError: Cannot read properties of undefined (reading 'url')
I come from a python basis, and in python, the latter would work well enough since functions are a first class citizen.
Why does the scoping work only when I use the arrow function? Does it have to do with the specifics of how node.js deals with binding and closures?
class ExternalAPIClient {
constructor() {
let appKey = "some-key"
this.env = {
"url": `some-url`,
"secretKey": "some-secret-key",
}
}
querySenderProfileCategory() {
return axios.get(
this.env.url + "/sender/categories",
{
headers: {
"Content-Type": "application/json;charset=UTF-8",
"X-Secret-Key": this.env.secretKey,
}
}
)
}
queryMessageList() {
return axios.get(
this.env.url + "/messages",
{
headers: {
"Content-Type": "application/json;charset=UTF-8",
"X-Secret-Key": this.env.secretKey,
}
}
)
}
}
const main = async () => {
let client = new NHNCloudClient();
const commands = {
"querySenderProfileCategory": () => client.querySenderProfileCategory,
"queryMessageList": client.queryMessageList,
}
const res = await client.querySenderProfileCategory(); // this works
const res = await commands.queryMessageList(); // this throws error
printObject(res.data)
};
main()