0

Pretty new to javascript classes. Im having trouble accessing a method of my class from a thread (ajax post). Ive also tried MyClass.this.coolFunction but nothing works! i also cant assign

var THIS = this;

in the constructor as to access a class variable you must use "this.variable" but this from a thread does not reference the class

class MyClass(){
    constructor(){
        this.THIS = this;
    }

    coolFunction(){

    }

    fetchData(id){
        $.post("ajax.php", {id: id},
                function (response) {
                    THIS.coolFunction();//HELP! (cant access coolFunction :(
                    this.coolFunction();//does not work
                }, "    json");
    }

}
MrRed
  • 677
  • 1
  • 6
  • 21
  • no that solution doesnt work. pls see my edit – MrRed Jan 29 '18 at 20:29
  • @Barmar can you please unmark this as a duplicate. As javascript classes work different to nested methods – MrRed Jan 29 '18 at 20:36
  • Not really. You access `this` the same way. – Barmar Jan 29 '18 at 20:37
  • Remember, classes are just syntactic sugar for functions and prototypes. – Barmar Jan 29 '18 at 20:38
  • Also: There's no constructor. Can you make a class without one? If so, how would that be different than just a function? – CodeAt30 Jan 29 '18 at 20:46
  • @Barmar i left the constructor out to leave focus on the problem. I have edited it. Your link does not solve the problem. To access a class variable you always use this. However in a thread or ajax call this will reference the thread. I would like to declare THIS for the class and not within every single method – MrRed Jan 29 '18 at 20:59
  • The constructor is irrelevant. Either use a fat arrow function, or declare a new variable `let self = this;` in the original function and use `self` instead of `this` in the callback. Just like the answers in that question say. – Barmar Jan 29 '18 at 21:01
  • `fetchData(id) { let self = this; $.post(... self.coolFunction(); ...);` – Barmar Jan 29 '18 at 21:03
  • Yeah i can do that but id prefer to just declare a self once in the constructor but it seems impossible. But definitely preferable to declaring a self in every method – MrRed Jan 29 '18 at 21:07

0 Answers0