【问题标题】:Javascript: outer method calling from nested functions [duplicate]Javascript:从嵌套函数调用外部方法[重复]
【发布时间】:2019-09-19 23:06:12
【问题描述】:

我想打电话给openSnackBar,但我遇到了异常。任何人都可以请帮助我如何处理来自嵌套函数的外部方法调用?

export class DetailsComponent implements OnInit, OnDestroy
{
updateTodoPromise.then(function (fulfilled) {
            // yay, you got a new phone
            this.openSnackBar('Task saved successfully!', 'CLOSE');
        })
        .catch(function (error) {
            // ops, mom don't buy it
            console.log(error.message);
            this.openSnackBar('Task saved successfully!','CLOSE');
        });

    }

    public openSnackBar(full: string, full2: string) {
        this.snackBar.open(full, full2, {
            duration: 5000,
        });
    }

【问题讨论】:

    标签: javascript typescript ecmascript-6 ecmascript-5


    【解决方案1】:

    使用 ES6 双箭头符号来保存 this 范围。

    export class DetailsComponent implements OnInit, OnDestroy
    {
    updateTodoPromise.then( fulfilled => { // <--- here
                // yay, you got a new phone
                this.openSnackBar('Task saved successfully!', 'CLOSE');
            })
            .catch( error => {  // <--- and here
                // ops, mom don't buy it
                console.log(error.message);
                this.openSnackBar('Task saved successfully!','CLOSE');
            });
    
        }
    
        public openSnackBar(full: string, full2: string) {
            this.snackBar.open(full, full2, {
                duration: 5000,
            });
        }
    

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 2018-05-27
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 2015-08-01
      • 2015-03-15
      相关资源
      最近更新 更多