为什么“this”在回调函数中变为空?

For*_*ugh 1 javascript firebase firebase-realtime-database angular

 ngOnInit() {
    console.log('this1: ', this);
    this.dbService.chats$.on('value', function(snapshot) {
        console.log('this2: ', this);
    });
}
Run Code Online (Sandbox Code Playgroud)

第一个 console.log 包含 Component 的所有字段,而第二个控制台日志为null

Sur*_*iya 6

匿名函数回调函数中, this 指的是当前上下文。

所以在你的例子中,它指的是回调函数下的上下文。

所以问题是如何访问 external this

有两种方法可以访问外部this

1. 箭头功能:

ngOnInit() {
    console.log('this1: ', this);
    this.dbService.chats$.on('value', (snapshot) => {
        console.log('this2: ', this);
    });
}
Run Code Online (Sandbox Code Playgroud)

2. 使用绑定:

ngOnInit() {
    console.log('this1: ', this);
    this.dbService.chats$.on('value', function(snapshot) {
        console.log('this2: ', this);
    }.bind(this));
}
Run Code Online (Sandbox Code Playgroud)


Ank*_*rma 5

使用以下代码:-

ngOnInit() {
    console.log('this1: ', this);
    this.dbService.chats$.on('value',(snapshot) => {
        console.log('this2: ', this);
    });
}
Run Code Online (Sandbox Code Playgroud)

这是因为thisnow 指的是function. 但是当您使用粗箭头时,=> this则指的是外部环境。