JavaScript: calling a function with a drop-down bracket returns the whole function as a string

I am creating a javascript object as below code:

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

i executed this function using this code obj.add and returned the entire function as a string: -

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

but later I will try to call the function again, including brackets like obj.add() , and it will return 30. Here, I can’t understand why I get such a different call by calling the function with obj.add and obj.add() ? What is the main difference between calling a function of objects with parentheses and the absence of parentheses. Can any body help?

+5
source share
6 answers

Without parentheses you get a link to a function, you do not call (execute) a function

Using parentheses you perform a 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; 
+5
source

You did not execute the function with obj.add , you only looked at it in the object and in the environment you were in to display the function as a string. You execute it by adding parentheses.

+3
source

Without a bracket, you will not name anything or return anything, this is just a link!

I assume you did something like this

 var result = ambes.add; console.log(result); 

and which does not call the function, it registers the actual contents of the add property, which , and the registration function registers the string contents of the function, and not what would happen if you called it.

+2
source

This is pretty simple: functionName just returns the body of the function, and functionName() executes the function and returns the return value (or undefined if there is no explicit return). The same principle works when a function is a property of an object, for example, you have obj.add .

+1
source

A function call requires () because it is a function call operator. To execute a function, you always need to include parentheses.

When you call ambes.add , you return the function object itself. If you do this inside console.log() or concatenate it with a string, JavaScript will return the function definition as a full string that explains the first result you received.

0
source

You must use () to call the function in JavaScript.

If you do not use parentheses, you simply refer to a function, which can be useful when you want to pass a function to another code block for deferred execution.

In your situation, because you want to call, right away, you should definitely use ()

 obj.add(); 
0
source

Source: https://habr.com/ru/post/1210265/


All Articles