I
I
Ivan Lapshin2019-01-31 21:47:22
JavaScript
Ivan Lapshin, 2019-01-31 21:47:22

What's the correct way to access a method in this way?

It so happened that in the class I need to refer to an already existing method. But I can't do it via this because I'm in an event handling function and this points to something else. So I assigned the method to the variable before the handler. The problem is that I don't understand why it is no longer possible to access class properties through this variable, although it is a reference to a class method. Below I will attach a simplified code without a handler, as an example, and the problematic code itself. And also, if you know how to fix the situation with this in the handler, then please write how.
An illustrative example:

class Test{
    constructor(a){
        this.a = a;
    }
    sqrA(){
        console.log(this.a * this.a)
    }
    testA(){
        let f = this.sqrA;
        console.log(f())
    }
}

obj = new Test(5);
obj.testA();

Error:
console.log(this.a * this.a)
^
TypeError: Cannot read property 'a' of undefined
Main code:
let curr_month = this.curr_mon;
        let curr_year = this.curr_year;
        let newMonth = this.setNewMonth;
        let baseEl = this.baseEl;
        $('#next').on('click',function (e) {
            curr_month++;
            if(curr_month == 12){
                curr_year++;
                curr_month = 0;
            }
            newMonth(baseEl, curr_month, curr_year);         

        })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zendor, 2019-01-31
@flame0399

Because you're assigning a function reference to a variable, it's just a reference, you need to look at the point of the call, and that's f(). Therefore, this will point to the global object, in the browser it is window. Use bind/call/apply and specify this explicitly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question