0

I'm trying to create a helper function. This function needs to reach some variables & objects of the context/class in which it is used. But, I could not achieve to do this. Is it possible to write functions to use like this?

Example:

// ExampleClass.js
const { demoArrowFunc, demoNormalFunction } = require('./MyHelpers')

class ExampleClass {
  exampleVar = "EXAMPLE VAR";

  constructor() {
    this.firstVar = 20
  }

  logClassVars() {
    console.log(this.exampleVar, this.firstVar);
  }

  tryArrows() {
    demoArrowFunc();
  }

  tryNormal() {
    demoNormalFunction()
  }
}

let example = new ExampleClass()
example.tryArrows() // Returns -> undefined undefined
example.tryNormal() // Returns -> undefined undefined

// Helpers.js
const demoArrowFunc = () => {
  console.log(this.exampleVar, this.firstVar);
}

const demoNormalFunction = function() {
  console.log(this.exampleVar, this.firstVar)
}

module.exports = {
  demoArrowFunc,
  demoNormalFunction 
}

Feel free to ask questions if I'm not clear. Thanks!

anileates
  • 78
  • 7
  • 1
    You can't. Having lexical `this` instead of contextual `this` is the **point** of arrow functions. Arrow functions are the wrong tool for your job. – Quentin Jul 23 '22 at 10:01
  • 1
    (You didn't ask about it but `tryNormal() { demoNormalFunction() }` doesn't work because you aren't passing it a context. Use the `call` or `apply` method). – Quentin Jul 23 '22 at 10:03
  • *"How to reach parent context...."* `this` isn't a "context," it's an object reference. "Context" means something completely different. – T.J. Crowder Jul 23 '22 at 10:04
  • 1
    @anileates - The simplest way to ensure that those functions (`demoArrowFunc` and `demoNormalFunction`) have access to the properties of the `ExampleClass` instance is to pass `this` into them as an argument. Then receive it as a parameter (`ex`, for instance), and use `ex.exampleVar`, etc. (Side note: `exampleVar` isn't a variable, it's a property.) – T.J. Crowder Jul 23 '22 at 10:05
  • 1
    So: `const demoArrowFunc = (ex) => { console.log(ex.exampleVar, ex.firstVar); };` and when calling from within `tryArrows`: `demoArrowFunc(this);`. – T.J. Crowder Jul 23 '22 at 10:09
  • Ok. I got the idea. Using `call` or passing `this` as an argument works. Thank you both @T.J.Crowder and @Quentin. – anileates Jul 23 '22 at 10:42

0 Answers0