Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this refers to the class in the function?

Usually when we use this, it refers to the class.

But in this case, this is dataChannel, how can I let this refers to VideoService again? Thanks

export class VideoService {
    dataChannel:any;

    setupPeerConnection() {
        this.dataChannel.onopen = this.dataChannelStateChanged;
    }

    dataChannelStateChanged() {
        // here this = dataChannel, how can I let this = VideoService
        console.log(this); 
    }
}
like image 332
Hongbo Miao Avatar asked Jan 01 '26 03:01

Hongbo Miao


1 Answers

You could use bind.

setupPeerConnection() {
    this.dataChannel.onopen = this.dataChannelStateChanged.bind(this);
}

bind creates a copy of a function with the specified object set as this.

like image 62
Mike Cluck Avatar answered Jan 03 '26 17:01

Mike Cluck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!