在 angular.js 中,没有 () 的函数调用与调用 with() 有什么不同吗?

In angular.js , Is function call without () different from call with()?

本文关键字:with 什么 调用 函数调用 js angular 没有      更新时间:2023-09-26

我写了一些关于$timeout服务的示例代码。

var myModule = angular.module('timerTest',[]);

        myModule.controller('counting',function($scope,$timeout)
        {
            var timerObject;
            var count =0;
            var countTime = function()
            {
                count++;
                console.log(count);
                $scope.value = count;
                timerObject = $timeout(countTime,1000);
            };
            $scope.startTimer = function()
            {
                console.log('timer start!');
                $timeout(countTime,1000);
            };
            $scope.endTimer = function()
            {
                console.log('End Timer');
                $timeout.cancel(timerObject);
            };
        });

在那个代码中 countTime 函数,当我写

timerObject = > $timeout(countTime(),1000);  

它调用countTime()非常快,因此它将使调用堆栈溢出。
但是当我写的时候

timerObject = $timeout(countTime,1000);

它工作得很好。有什么不同吗?

timerObject = $timeout(countTime(),1000)立即在该行上调用countTime,并将结果传递给$timeout每当你在函数名称后面加上括号时,这意味着你在那里调用函数 - 因为你在函数的每次迭代中都这样做,它会导致它无休止地重复,因此堆栈溢出。

另一方面,timerObject = $timeout(countTime,1000)countTime函数本身传递给$timeout - 这是使用该服务的正确方式,并且将导致$timeout在大约 1000 毫秒后调用countTime