Javascript:从嵌套函数调用外部方法

标签 javascript typescript ecmascript-6 ecmascript-5

我要调用openSnackBar但我得到异常(exception)。任何人都可以帮助我如何处理嵌套函数的外部方法调用?

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,
        });
    }

最佳答案

使用 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,
        });
    }

关于Javascript:从嵌套函数调用外部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55935287/

相关文章:

javascript - 用 let 或 const 声明的变量是否被提升?

Node.js 过滤其中一个值重复但另一个值不重复的对象数组

javascript - 如何根据连接表的列对 Bookshelf.js 查询的结果进行排序?

javascript - 管道放置下划线底部字母 Angular

angular - 使用 Promise 时如何进行条件检查并返回自定义对象?

typescript - 返回类型化索引的通用数组

javascript - 从 PHP 文件发回消息

javascript - 需要在按下回车键时触发该功能

javascript - 如何将此 blob 字段发送到服务器?

javascript - 使用 mocha 测试依赖于环境变量 process.env.APP_ENV 的配置模块