TypeError: "this..." is not a function

TypeError: "this..." is not a function

我定义hostService如下。 senario 是我先在控制器中调用 hostService.addListener(),然后控制器可能会通过 $rootSceop.$emit 发出消息,hostService 应该处理它。

app.service('hostService', ['$rootScope', function ($rootScope) {    
    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            this.button()
        })
    }

但是,问题是上面的代码引发了一个错误:

TypeError: this.button is not a function

有人知道怎么解决吗?

我用 this 对象创建一个自变量来解决这个问题,然后你可以从不同的范围调用它:

app.service('hostService', ['$rootScope', function ($rootScope) {    

    var self = this

    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            self.button()
        })
    }