0

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.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Cute Bike
  • 1
  • 1
  • 2
    Arrow functions *close over* the value of `this`, so what you see in those arrow functions is the value `this` has in the scope where they're created. You haven't shown any context for them, but it sounds like the one in `setStatus.js` is defined somewhere where `this` is an empty object and the one in `start.js` is defined somewhere (such as the constructor) where `this` refers to the Client instance. If you want `this` to be controlled by how the function is called, don't use an arrow function; otherwise, make sure you're closing over the right value of `this`. – T.J. Crowder Sep 27 '20 at 14:02
  • 1
    I changed setStatus from an arrow function and it worked perfectly, thanks! – Cute Bike Sep 27 '20 at 14:30

0 Answers0