1

I'm learning javascript : I try to access "this" in the function "checkAndChange" but, according to how I declare and export my function , "checkAndChange" can't call previous functions (this.isErr) because sometimes this refers to "global".

I try it with 3 ways , 1 works but i don't know why. This is an example :

exports.isErr = (err) => {
    return err instanceof Error;
}
// This way works : 
exports.checkAndChange = (obj) => {
    console.log(this); // Here , "this" contains "isErr".
    if (this.isErr(obj))
        return "Error";
    else
        return "It's Okay"
}
function checkAndChange(obj){
    console.log(this); // But not here , "this" refers to "global".
    if (this.isErr(obj)) // TypeError: this.isErr is not a function
        return "Error";
    else
        return "It's Okay"
exports.checkAndChange = checkAndChange; // here i have to bind(this) to make it work and i don't know why.
}
isherwood
  • 46,000
  • 15
  • 100
  • 132
mickatdj
  • 21
  • 2
  • 1
    Don't confuse `this` scope with module scope. `this` has nothing to do with modules – Cristian Traìna Sep 13 '19 at 12:57
  • [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions) – palaѕн Sep 13 '19 at 12:58
  • `this` inside a node module does not refer to the global object, it refers to `exports` itself. You can add `console.log(this === exports)` at the top to verify that. And since arrow functions resolve `this` lexically, `this` inside the arrow function refers to the `this` of the module. Whether or not your second example works really depends on how the function is called. – Felix Kling Sep 13 '19 at 12:59

0 Answers0