Reputation: 2662
Just wondering, having the following simple code:
var object1 = {
name: function (){
return 'myName';
},
surname: function (){
return 'mySurname';
}
};
Why does JS returns function()
in this case object1.name ?
Why does JS returns the expected result myName
if I call object1.name() ?
Upvotes: 0
Views: 105
Reputation: 160170
name
returns what name
is–in this case, a function.name
by appending ()
, i.e., name()
, returns a value–the string "myName"
.My answer to When do I use parenthesis and when do I not? provides more details.
Upvotes: 2
Reputation: 43810
because in object1.name
you are calling the function declaration
and in object1.name()
you are calling the function
Upvotes: 1
Reputation: 11342
object1.name;//Returns the function declaration
object1.name();//Calls the function and returns its value
It works like the following code:
var myFn = function(){
return "This is the return value of this function";
}
alert(myFn);//Alerts the myFn function's declaration
alert(myFn());//Alerts "This is the return value of this function"
Upvotes: 1