ambes ambes - 17 days ago 7
Javascript Question

JavaScript: calling a function with out parenthesis return's whole function as string

I create a javascript Object as below code:

var obj={
a : 10,
b : 20,
add : function(){
return this.a + this.b;
},
};


i executed the function with this code
obj.add
and it return the whole function as string like this:-

function(){
return this.a + this.b;


but later i try by call the function again including the parenthesis like
obj.add()
and it return the value 30. Here i couldn't figure out why i get such different out put upon calling the function with
obj.add
and
obj.add()
? What is the main difference between calling an objects function with parenthesis and with out parenthesis Can any body help??

Answer

Without parentheses, you're retrieving a reference to the function.

With parentheses, you're executing the function.

function a() {
  return 2;
}

var b = a(); // called a, b is now 2;
var c = a; // c is referencing the same function as a
console.log(c); // console will display the text of the function in some browsers
var d = c(); // But it is indeed a function, you can call c(), d is now 2;

Comments