Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript return method

Tags:

javascript

I'am new in javascript. I can't understand why the function returns T1 object (not just string 'hi') in the following example.

 function T1(){
    return 'hi';
 }
 function T(){
    return new T1();
}
T();

output: T1

And returns function in the following example

 function T1(){
    return function(){ return 'hi'; }
 }
 function T(){
    return new T1();
}
T();

output: function (){ return 'hi' }

Why does the first example returns an object (not the string "hi", what is expected to happen) and the second returns the function body that is returned from the first function (not the expected object)?

Please explain this result. Thank you)

like image 576
user1314034 Avatar asked Jan 18 '23 00:01

user1314034


1 Answers

The new operator returns the object created by the operator unless the constructor function returns a different object. Any non-object return value of the constructor function is ignored, which is why when you return hi you don't see this.

Section 13.2.2 ("[[Construct]]") of the specification, which is referenced by Section 11.2.2 ("The new operator").

like image 188
Chris Gessler Avatar answered Jan 22 '23 10:01

Chris Gessler