0

I have a class and it has a constructor. I assign a class variable by this.something and it is not being accessed in some another function inside the same class.

Following is my class

class A {
    some_func() {
        console.log(this.var1);  // this is giving undefined
    }
    constructor(socket, var1) {
        this.socket = socket;
        this.var1 = var1;

        this.socket.on('some event', some_func);
    }
}

Inside the some_func function the variable is undefined. How do i fix that?

bradley101
  • 723
  • 6
  • 19
  • 1
    Do a `console.log(this);` inside `some_func()`. Check if that actually refers to class a or socket. You might need to call it like `some_func.bind(this)` – palaѕн Mar 05 '18 at 16:02
  • When you assign a function your `this` context doesn't get automatically attached to the function invocation,.. To get around this you can do -> `this.some_func.bind(this)` – Keith Mar 05 '18 at 16:06
  • @palash Right! the `bind()` method did the job! cheers! – bradley101 Mar 05 '18 at 16:29

1 Answers1

0

I don't see a problem with your code. Are you definitely instantiating the variable before using the method? As shown below

class A {

    constructor(socket, var1) {
        this.socket = socket;
        this.var1 = var1;

        //this.socket.on('some event', this.some_func);
    }
    
    some_func() {
        console.log(this.var1);  // this is giving undefined
    }
}

var instanceA = new A('socket', 'var')

instanceA.some_func() // Returns 'var'
Pandelis
  • 1,854
  • 13
  • 20
  • 1
    `I don't see a problem ` because your not doing the same thing, change the `this.socket.on`, to a simple `setTimeout` and you will get the same problem. – Keith Mar 05 '18 at 16:07
  • make sure you're refering to this.some_func not some_func – Pandelis Mar 05 '18 at 16:10
  • That is not what i wanted. setTimeout wont work for me – bradley101 Mar 05 '18 at 16:22
  • 1
    @Shantanu That's not what I'm suggesting, my suggestion was for emulating the problem your seeing. And why using `bind` as I & palaѕн suggested. – Keith Mar 05 '18 at 17:07