ค้นหาเว็บไซต์

javascript - ฉันจะทำให้ this อ้างอิงถึงคลาสในฟังก์ชันได้อย่างไร?


โดยปกติเมื่อเราใช้ this มันจะอ้างอิงถึงคลาส

แต่ในกรณีนี้, this คือ dataChannel, ฉันจะทำอย่างไรให้ this กลับหมายถึง VideoService อีกครั้ง? ขอบคุณ

export class VideoService {
    dataChannel:any;

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

    dataChannelStateChanged() {
        // here this = dataChannel, how can I let this = VideoService
        console.log(this); 
    }
}

คำตอบ #1

คุณสามารถใช้ bind ได้

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

bind สร้างสำเนาของฟังก์ชันโดยตั้งวัตถุที่ระบุเป็น this

คำตอบ #2

ผูกบริบทอย่างชัดเจนด้วย Function.prototype.bind:

export class VideoService {
    dataChannel:any;

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

    dataChannelStateChanged() {
        console.log(this); 
    }
}

หรือใช้ฟังก์ชันลูกศรเพื่อรักษาสโคปตามตัวอักษร:

export class VideoService {
    dataChannel:any;

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

    dataChannelStateChanged() {
        console.log(this); 
    }
}

บทความที่เกี่ยวข้อง