Jackie Chan
Jackie Chan

Reputation: 2662

Javascript OOP Methods

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

Answers (3)

Dave Newton
Dave Newton

Reputation: 160170

  1. Referencing name returns what name is–in this case, a function.
  2. Calling 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

Ibu
Ibu

Reputation: 43810

because in object1.name you are calling the function declaration

and in object1.name() you are calling the function

Upvotes: 1

Danilo Valente
Danilo Valente

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

Related Questions