All the four codes below does the same thing. Hope you have a better understanding on function declarations. :)
Code 1:
.factory('cribs',function(){
var data = 3.142;
function getcrib(){
return data;
}
return{
getcrib: getcrib
}
})
//console.log(cribs.getcrib()) outputs 3.142
Explanation:
- An object is returned.
- This object has a property of
getcrib, which reference the function whose name is also getcrib.
Code 2:
.factory('cribs', function() {
var data = 3.142;
return {
getcrib: function() {
return data;
}
}
})
//console.log(cribs.getcrib()) outputs 3.142
Explanation:
- An object is returned.
- This object has a property of
getcrib, which reference an anonymous function. (anonymous is a function without a name)
Code 3:
.factory('cribs',function(){
var data = 3.142;
function GET_PI_VALUE(){
return data;
}
return{
getcrib: GET_PI_VALUE
}
})
//console.log(cribs.getcrib()) outputs 3.142
Explanation:
- An object is returned.
- This object has a property of
getcrib, which reference a function whose name is called GET_PI_VALUE. This is the same case as code 1
Code 4:
.factory('cribs', function() {
var data = 3.142;
return {
getcrib: function GET_PI_VALUE() {
return data;
}
}
})
//console.log(cribs.getcrib()) outputs 3.142
Explanation:
- An object is returned.
- This object has a property of
getcrib, which reference a function whose name is called GET_PI_VALUE. This is the same case as code 3.
Code 5
.factory('cribs', function() {
var data = 3.142;
return {
getcrib: function GET_PI_VALUE() {
return data;
}
}
})
//console.log(cribs.GET_PI_VALUE()) gives an error, complaining GET_PI_VALUE is not a function.
Explanation:
- An object is returned.
- This object has a property of
getcrib
GET_PI_VALUE is totally shadowed, hence error. The function of GET_PI_VALUE itself was NOT returned, only the reference(via getcribs) is returned.
getcribis a reference to the function declared in the lines above. The property namegetcribonly matters to the user of the factory.var t = function getcrib(){ ..} return tas such?