"this"(对象)在使用 $timeout 调用 angularjs 函数时未定义
"this" (object) is undefined when calling angularjs function with $timeout
我有一个 angular 服务来管理我的屏幕提醒:
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);
}
}
});
设置消息工作正常(从 angular 控制器调用)并设置超时变量 OK,但是当超时内调用的函数 (unsetMessage) 在 5 秒延迟后运行时,代码抛出一个错误 this is undefined
。为什么它不将自己识别为一个对象,我该如何实现我想要做的事情?
一种可能性是在回调中使用捕获的 self
和 apply
以便传递正确的上下文:
if (timed) {
unsetMsg = $timeout(function() {
self.unsetMessage.apply(self);
}, 5000);
}
我有一个 angular 服务来管理我的屏幕提醒:
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);
}
}
});
设置消息工作正常(从 angular 控制器调用)并设置超时变量 OK,但是当超时内调用的函数 (unsetMessage) 在 5 秒延迟后运行时,代码抛出一个错误 this is undefined
。为什么它不将自己识别为一个对象,我该如何实现我想要做的事情?
一种可能性是在回调中使用捕获的 self
和 apply
以便传递正确的上下文:
if (timed) {
unsetMsg = $timeout(function() {
self.unsetMessage.apply(self);
}, 5000);
}