-1

I'm looking for a convenient way of maintaining the original context in which a js file operates in at page load.

Technically, a function is called in the js which triggers the construction of someClass

someClass contains a series of methods which are meant to be part of an API and looks something like:

class someClass{
   procGenFunction(){
       /* code that procedurally generates a an element <=> " BTN " */
       BTN.on('click', fn_called_on_click);
   }

   fn_called_on_click(){
      this.doWhatever(); <--- I need the original context of "THIS" at this point.
   }
}

Because JavaScript, the this keyword references different objects based on where it's called from.

I want to conserve the original value of this whenever calling any method which is part of the API.

The original value of this is, as far as I'm concerned, #document.

TL;DR: I want to always use this in its original form regardless of where the API calls any function which references that keyword.

It should be worth mentioning that I "absolutely have to" implement this in the most dev-friendly way possible, a.k.a. if possible, not pass this as an argument to that function every time I want to call it.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
EverNight
  • 964
  • 7
  • 16
  • 1
    use arrow functions or bind this in constructor – Avinash Thakur Jul 28 '21 at 19:34
  • 1
    *“The original value of this is, as far as i'm concerned, #document”* Seems like this “original value of `this`” could be accessed using one of `window`, `document`, or `document.documentElement` (the latter two not actually being “original values of `this`”). – Ry- Jul 28 '21 at 19:37
  • 2
    While what you're trying to do is possible (through either `bind()` or arrow functions), it would be incredibly bad practice, confusing to other developers who have to maintain the code, and cause a lot of unnecessary headaches. I would strongly advise you don't do it. – Rory McCrossan Jul 28 '21 at 19:39
  • @AvinashThakur thank you. – EverNight Jul 28 '21 at 20:05
  • @RoryMcCrossan thank you. – EverNight Jul 28 '21 at 20:05
  • @RoryMcCrossan how is it incredibly bad practice ? bind and arrow functions are popularly used for this purpose, arrow functions being more popular and recommended way of doing this. Moreover, the core purpose of arrow functions is solving the same issue of `this`. – Avinash Thakur Jul 29 '21 at 03:38

1 Answers1

1

Try this inside of a constructor:

class someClass {
   constructor (props) {
      super(props)
      this.doWhatever = this.doWhatever.bind(this)
   }
}
Dylan
  • 43
  • 5