johnypower johnypower - 7 months ago 24
Javascript Question

Parameters in javascriptmethods

I haven't understand the function definition inside a method in javascript.
For example in AngularJS I have th code:

sth.controller('ctrlname', function ($scope, $ionicModal, par3, par4){
//code
});


I also have th code:

var f = function (par5,par6){
return par5 + par6;
}


If I call f(2,3) I get the result 5.

So in controller and other similar examples I choose arbitrary names for the parameters inside function or variables that exists previously?

Answer

As @MikeFeltman said, you can use any name for your functions' arguments BUT Angular as its own logic for dependency injection and it can use argument's name to identify which piece of software your controller/service/etc depends on.

Let's create a B controller that depends on a A service:

angular.module("testModule",[])
.service("A",function(){
//do stuff
})
.controller("B",function(A){
//do other stuff
});

Angular injector, will look at the B constructor's arguments (here A) and try to find the expected service.

But you can name your arguments as you want :

angular.module("testModule",[])
.service("A",function(){
//do stuff
})
.controller("B",["A",function(dontCareAboutVarName){
//do other stuff
}]);

Here the injector, won't look at the function's arguments as it will find an array describing the dependencies and, the last item will be the controller constructor.

Please, take a look at the documentation about angular's injector