Javascript 为什么;这";在回调函数中变为null?
第一个console.log包含组件的所有字段,而第二个console日志包含空值。请使用以下代码:-Javascript 为什么;这";在回调函数中变为null?,javascript,angular,firebase,firebase-realtime-database,Javascript,Angular,Firebase,Firebase Realtime Database,第一个console.log包含组件的所有字段,而第二个console日志包含空值。请使用以下代码:- ngOnInit() { console.log('this1: ', this); this.dbService.chats$.on('value', function(snapshot) { console.log('this2: ', this); }); } 这是因为此现在指的是函数中的上下文。但是,当您使用胖箭头时,此表示外部环境。使用以下
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', function(snapshot) {
console.log('this2: ', this);
});
}
这是因为此
现在指的是函数
中的上下文。但是,当您使用胖箭头时,此表示外部环境。使用以下代码:-
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', function(snapshot) {
console.log('this2: ', this);
});
}
这是因为
此
现在指的是函数
中的上下文。但是当您使用胖箭头时,此指的是外部环境。当您调用匿名函数时,要维护此
的实例,请使用箭头函数
而不是
使用
调用匿名函数时,要维护
this
的实例,请使用箭头函数
而不是
使用
有时,在函数下,此的上下文可能不可用。 请参见这是一个特殊的关键字,其用法完全取决于如何/在何处以及何时与函数一起使用 试试下面的改变,希望它能解决你的问题
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', (snapshot) => {
console.log('this2: ', this);
});
}
有时,在函数下,此的上下文可能不可用。 请参见这是一个特殊的关键字,其用法完全取决于如何/在何处以及何时与函数一起使用 试试下面的改变,希望它能解决你的问题
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', (snapshot) => {
console.log('this2: ', this);
});
}
在匿名函数或回调函数中,这指的是当前上下文 因此,在您的示例中,它引用回调函数下的上下文 所以问题是如何访问外部
此
您可以通过两种方式访问外部此
1。箭头功能:
2。使用绑定:
在匿名函数或回调函数中,这指的是当前上下文 因此,在您的示例中,它引用回调函数下的上下文 所以问题是如何访问外部
此
您可以通过两种方式访问外部此
1。箭头功能:
2。使用绑定:
我真是太感谢你了!我真是太感谢你了!
ngOnInit() {
console.log('this1: ', this);
let that = this; // you can give any name to variable.
that.dbService.chats$.on('value', function(snapshot) {
console.log('this2: ', that);
});
}
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', (snapshot) => {
console.log('this2: ', this);
});
}
ngOnInit() {
console.log('this1: ', this);
this.dbService.chats$.on('value', function(snapshot) {
console.log('this2: ', this);
}.bind(this));
}