从嵌套函数访问函数属性

Accessing of functions properties from nested functions

本文关键字:函数 属性 访问 嵌套      更新时间:2023-09-26

从嵌套函数访问函数属性时遇到问题。我肯定我错过了什么,但在谷歌上搜索了3个小时后,我不知道该找什么。背景:我想在angularjs中添加一个控制器,在一定时间后重新加载页面。我的问题是从"this.reloadTicker()"访问"this.enabled"。重命名控制器功能然后访问它们的想法是行不通的。一种解决方案是将所有内容存储在"$scope"中,但有更好的解决方案吗?

我的代码:

ctrls.controller("reloaderCtrl", function reloader($scope) {
    this.enabled = true;
    this.paused = false;
    this.maxSecs = 30;
    this.secs = 30;
    this.reloadTicker = function() {
        if (reloader.enabled && !reloader.paused) {
            if (reloader.secs > 0) {
                reloader.secs--;
            } else {
                reloader.reload();
                reloader.secs = reloader.maxSecs;
            }
            $scope.$apply();
        }
        setTimeout(this, 1000);
    }
    this.reload = function() {
        $scope.$emit('doReload');
    }
    setTimeout(this.reloadTicker, 1000);
});

您需要在一些变量中捕获this

ctrls.controller("reloaderCtrl", function ($scope) {
    var vm = this;
    vm.enabled = true;
    vm.paused = false;
    vm.maxSecs = 30;
    vm.secs = 30;
    vm.reloadTicker = function() {
        if (vm.enabled && !vm.paused) {
            if (vm.secs > 0) {
                vm.secs--;
            } else {
                vm.reload();
                vm.secs = vm.maxSecs;
            }
            $scope.$apply();
        }
        setTimeout(this, 1000);
    }
    vm.reload = function() {
        $scope.$emit('doReload');
    }
    setTimeout(vm.reloadTicker, 1000);
});

PS。我建议使用Angular $timeout而不是setTimeout(https://docs.angularjs.org/api/ng/service/$timeout)

PSS。我建议你去看看约翰·帕帕的《角度风格指南》。这是一本非常好的读物(https://github.com/johnpapa/angular-styleguide)