I've got a problem with the "this" keyword in node, In my library, I have a constructor called "Client" and its prototype has a lot of functions. One of the functions "start" recognizes "this" as the Client instance and that's good. But my problem is that the other function "setStatus" recognizes "this" as a plain object. I have a directory where I keep all modules of Client's prototype functions and load them in using fs so I don't know if that is a cause for this problem. Here's my code:
setStatus.js
let setStatus = (update) => {
console.log(this) //Isn't the Client instance, just plain object {}
}
start.js
let start = (val) => {
console.log(this) //Has the value of the Client instance
}
bundle.js (Loads constructors and methods into 1 object)
let unpack = require("./func/unpack.js")
let rbx = {};
const classUnpack = unpack.run("class")
Object.keys(classUnpack).forEach(cls => {
let objCls = classUnpack[cls]
let clsUnpack = unpack.run(cls.toLowerCase())
Object.keys(clsUnpack).forEach(method => {
objCls.prototype[method] = clsUnpack[method]
})
rbx[cls] = objCls
})
unpack.js (Runs require on every module in a directory)
let path = require("path");
let dir = __dirname;
let fs = require("fs");
function unpack(pth, st) {
let pr = {}
fs.readdirSync(path.join(dir, `/../${pth}`)).forEach(mod => {
if (!st) {
pr[mod.split(".")[0]] = require(`../${path.join(pth, mod)}`);
} else {
st[mod.split(".")[0]] = require(`../${path.join(pth, mod)}`);
}
});
if (!st){
return pr
}
else{
return st
}
}
Thanks.