Javascript 如何从委托函数(回调)访问服务变量
我使用的是一个服务,它有一个变量,需要通过该服务进行更新。但我无法访问匿名函数/委托函数中的varJavascript 如何从委托函数(回调)访问服务变量,javascript,angularjs,callback,angularjs-service,Javascript,Angularjs,Callback,Angularjs Service,我使用的是一个服务,它有一个变量,需要通过该服务进行更新。但我无法访问匿名函数/委托函数中的var (function() { 'use strict'; angular .module('yoTest') .service('mainService', mainService); /** @ngInject */ function mainService($timeout) { this.counter = 1; this.updat
(function() {
'use strict';
angular
.module('yoTest')
.service('mainService', mainService);
/** @ngInject */
function mainService($timeout) {
this.counter = 1;
this.updateCounter = function updateCounter() {
this.counter++;
$timeout(updateCounter, 500);
}
this.updateCounter();
}
})();
如果我通过$timeout
重新加载“updateCounter”,我会得到一个错误,为什么
如何通过超时和委托/回调访问它?问题在于调用刚刚传递的函数时,
updateCounter
函数引用位于$timeout
回调中。因此,当$timeout
尝试评估该函数时,此
属于updateCounter
将是它自己的此
,而不是考虑主服务的此
。在这种情况下,您必须使用.bind(this)
在ES6中,使用Fat Arrow
函数也可以实现同样的效果
$timeout(() => { updateCounter () }, 500);
作为Pankaj答案的替代方案,您可以将当前上下文绑定到变量,并使用该变量引用属性和函数
function mainService($timeout) {
var service = this;
this.counter = 1;
this.updateCounter = function updateCounter() {
service.counter++;
console.log(service.counter)
$timeout(service.updateCounter, 500);
}
this.updateCounter();
}
很有帮助,但如何更新控制器/视图绑定@n00n可能是实现相同功能的一种方式
function mainService($timeout) {
var service = this;
this.counter = 1;
this.updateCounter = function updateCounter() {
service.counter++;
console.log(service.counter)
$timeout(service.updateCounter, 500);
}
this.updateCounter();
}