Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么;这";在回调函数中变为null?_Javascript_Angular_Firebase_Firebase Realtime Database - Fatal编程技术网

Javascript 为什么;这";在回调函数中变为null?

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); }); } 这是因为此现在指的是函数中的上下文。但是,当您使用胖箭头时,此表示外部环境。使用以下

第一个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);
    });
}

这是因为
现在指的是
函数
中的上下文。但是当您使用胖箭头时,此
指的是外部环境。

当您调用匿名函数时,要维护此
的实例,请使用箭头函数

而不是

使用


调用匿名函数时,要维护
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));
}