All of the following code snippets achieve the same outcome. Hopefully, this will enhance your comprehension of function declarations. :)
Sample 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 includes a property named
getcrib
, which points to the function with the same name.
Sample 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 contains a property called
getcrib
, pointing to an anonymous function (a function without a specific name).
Sample 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 named
getcrib
, referring to a function named GET_PI_VALUE
. This mirrors the structure in code snippet 1.
Sample 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 includes a property named
getcrib
, which refers to a function named GET_PI_VALUE
. This closely resembles the setup in code snippet 3.
Sample Code 5
.factory('cribs', function() {
var data = 3.142;
return {
getcrib: function GET_PI_VALUE() {
return data;
}
}
})
//console.log(cribs.GET_PI_VALUE()) results in an error message indicating that GET_PI_VALUE is not recognized as a function.
Explanation:
- An object is returned.
- This object contains a property named
getcrib
- The presence of
GET_PI_VALUE
is entirely obscured, causing an error. The actual function of GET_PI_VALUE
was NOT returned, only its reference through getcribs
is returned.