Issue
I'm learning AngularJS, and someone wrote this code:
.factory('cribs',function(){
var data = [{
name: "jack",
last: 'doe'
},{
name: 'hazel',
last: 'man'
}
];
function getcrib(){
return data;
}
return{
getcrib: getcrib // what the heck does this mean?
}
})
I'm baffled with the return line... he returned an object of getcrib
with a function that returns the data? Does the getcrib
at the beginning need to be the same exact case?
Solution
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 alsogetcrib
.
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 calledGET_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 calledGET_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 ofGET_PI_VALUE
itself was NOT returned, only the reference(via getcribs) is returned.
Answered By - CozyAzure
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.