使用$ timeout调用angularjs函数时,"this"(对象)是未定义的

Ben*_*ury 3 service this angularjs

我有一个角度服务来管理我的屏幕警报:

angular.module('theapp')
.factory('Alerts', function ($timeout) {

  var unsetMsg = null;

  return {

    alertType: null,
    alertTitle: null,
    alertMessage: null,

    setMessage: function(type, title, message, timed) {     
        var self = this;
        $timeout.cancel(unsetMsg);
        self.alertType = type;
        self.alertTitle = title;
        self.alertMessage = message;

        if (timed)
        {
            unsetMsg = $timeout(self.unsetMessage,5000);
        }
    },

    unsetMessage: function() {
        this.alertType = null;
        this.alertTitle = null;
        this.alertMessage = null;   
        $timeout.cancel(unsetMsg);
    }
  }
  });
Run Code Online (Sandbox Code Playgroud)

设置消息正常工作(从角度控制器调用)并设置超时变量OK,但是当超时(unsetMessage)内调用的函数在5秒延迟后运行时,代码会抛出错误this is undefined.为什么它不会将自己视为一个对象,我如何实现我想要做的事情?

Dar*_*rov 5

一种可能性是使用捕获它selfapply它在回调上,以便传递适当的上下文:

if (timed) {
    unsetMsg = $timeout(function() {
        self.unsetMessage.apply(self);
    }, 5000);
}
Run Code Online (Sandbox Code Playgroud)