Utilizing the calculate()
function as a private method within the confines of the CartController
is recommended if the function does not need to be accessed from the view. By marking it as a private function, it signals that its usage should be limited within the controller itself and caution should be exercised when considering its use in the view. Furthermore, accessing objects within the scope of the CartController
is possible from within the calculate
function, including objects passed as parameters to the controller.
A proper JavaScript function
declaration allows for easy referencing by name. A common practice is declaring functions beforehand and then assigning them to properties of an object (such as $scope
):
function someFn(...) { ... }
function someOtherFn(...) { ... }
...
$scope.someFn = someFn
In this example, clarity is prioritized by making someFn
accessible while keeping someOtherFn
private.
It's worth noting that defining functions like function nameFn(...){...}
is referred to as a function statement, whereas a similar approach can be taken with var nameFn = function(...) {...}
(known as a function expression). The key distinction lies in the fact that:
someFn();
var someFn = function(...) {...}
is invalid, while:
someFn();
function someFn(...) {...}
is acceptable.
Situations may arise where using the latter pattern becomes necessary, as illustrated in my response to a query about Angular injector decoration here.