0

Is there a better way to avoid utilizing self = this because it's conflicting with one of my plugin?

class Test {
    constructor() {
        self = this;
    }
      
    fetchURL(url) {
      fetch(url)
        .then(function (response) {
           self.func1();
        });
     }

    func1() {
        console.log("func1");
        self.func2();
    }

    func2() {
        console.log("func2");
    }
}


document.getElementById("basicFetchButton").addEventListener("click", function () {
    let test = new Test();
    test.fetchURL('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js')
    // Loading the jQuery code

});
<input type="button" id="basicFetchButton" value="Try it">
rj487
  • 4,476
  • 6
  • 47
  • 88
  • Looks like self is a global variable here. Is this intended? – Wiktor Zychla Aug 02 '22 at 21:56
  • How is it interfering with a plugin? Because you’re using a global “self” instead of attaching it to the instance using “this” or using a different variable name? Or because you’re not using arrow functions to bind “this” automatically? – Dave Newton Aug 02 '22 at 21:56
  • @DaveNewton that's the unknown mystery, all I know is the `self=this` breaks one of the date-picker. – rj487 Aug 02 '22 at 22:01
  • @WiktorZychla what do you mean by a global variable? It's capsulated in a class. – rj487 Aug 02 '22 at 22:02
  • 3
    @rj487 No it isn’t; it’s not “this.self” or declared in the constructor. – Dave Newton Aug 02 '22 at 22:05
  • @DaveNewton I see your point, yes it's a global variable and how do I prevent it? – rj487 Aug 02 '22 at 22:07
  • The duplicate has full details, but the short version is that you should remove the constructor, use `this` in place of `self`, and use `(response) => {` instead of `function (response) {` so that function doesn’t have its own separate `this` value. – Ry- Aug 02 '22 at 22:08
  • Either use [an arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions): `.then(response => { this.func1(); });` or `bind` `this`: `.then(this.func1.bind(this));`, and then you can remove `self` altogether. – Andy Aug 02 '22 at 22:09
  • The arrow function helps. I am keeping this question since the other link doesn't have an example in class. – rj487 Aug 02 '22 at 22:25
  • If someone answers it, I will pick it as the answer. – rj487 Aug 02 '22 at 22:26

0 Answers0