角度和普通javascript函数,最佳实践
这种向(角度)脚本添加函数的方式是否有任何区别(可能在性能上),或者它们本质上是等效的: 选项1:控制器内部的功能角度和普通javascript函数,最佳实践,javascript,angularjs,Javascript,Angularjs,这种向(角度)脚本添加函数的方式是否有任何区别(可能在性能上),或者它们本质上是等效的: 选项1:控制器内部的功能 AngularApp.component('component', { templateUrl: '/domain/app/component.html' , controller: function ($scope,$rootScope,api) { $scope.var = false; getBackendData();
AngularApp.component('component', {
templateUrl: '/domain/app/component.html'
, controller: function ($scope,$rootScope,api) {
$scope.var = false;
getBackendData();
//get data about available io_engines from the backend
function getBackendData() {
console.log("loading backend data...");
api.get().then(
function (response) {
console.log("Backend data loaded.");
})
.catch(function (err) {
console.log("Error getting data from backend");
console.log(err);
});
}
}
});
选项2:控制器外部的功能
AngularApp.component('component', {
templateUrl: '/domain/app/component.html'
, controller: function ($scope,$rootScope,api) {
$scope.var = false;
getBackendData();
}
});
//get data about available io_engines from the backend
function getBackendData() {
console.log("loading backend data...");
api.get().then(
function (response) {
console.log("Backend data loaded.");
})
.catch(function (err) {
console.log("Error getting data from backend");
console.log(err);
});
}
我(想)理解第二个选项中的
getBackendData()
成为一个全局函数,但我不太清楚它的含义。如果在组件中定义一个函数,那么每个组件实例将有一个函数定义,因此理论上需要更多内存
在第二个示例中,每个应用程序只有一个函数
但这种差异确实是学术性的。更大的问题在于这些功能应定义在(或作为)服务中,因此它们可以是:
- 测试
- 可能在其他地方重复使用
- 在组件测试中模拟
- 测试
- 可能在其他地方重复使用
- 在组件测试中模拟
选项1更好,因为您没有污染全局范围。可以说,这不是一个好的做法。我建议您遵循托德格言中的风格指南: