0

I have a js class that contains many functions which proceed_data() contains Jquery $.post function and callback(function (data)) does not allow to access preload() class and constructor class in its own.

Please assist me, thanks.

    class GridDisplay {
        constructor(current_page){
            this.current_page = current_page;
            this.csrf_token = "ABCDE"
       }
       
       preload(x, y){

             return(x+y);
       }


        proceed_data(){


            $.post("/api/", 
            {'csrfmiddlewaretoken' : this.csrf_token, 
            'page_no' : this.current_page,  
            function (data) {

               grid_item = this.preload(data.x, data.y)

            }

            })

        }

  • use an arrow function for `function (data) {` ... or bind that function to `this`, or use `var _this = this;` outside that callback function and `_this.get_grid_item` inside it - then learn how `this` works :p – Bravo Jul 18 '21 at 16:01

1 Answers1

0

I assume your problem is that you can't access this within the callback?

You probably want to use arrow function expressions, also called "lambdas" at times, a term sometimes used for anonymous functions.

The main difference between regular function declarations and arrow function expressions is that they don't "reserve" the this keyword. It will still point towards the this from the previous scope:

function a() {
    console.log(this);
    return () => {
        console.log(this); // Prints the same as above, no matter where this function is called from
    };
}

const obj = { a };
const f = obj.a();
f();
// ^ Prints `obj` twice

You can use data => { ... } as your callback function so you can still access this from the class method.

Alternatively, save this in a local variable beforehand, although this is seen as an older pre-arrow-functions technique:

function a() {
    const _this = this;
    console.log(_this);
    return function() {
        console.log(_this); // Prints the same as above, due to the saved variable and function scoping
        console.log(this); // Mind that you don't know what this will print!
    };
}
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31