Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  171] [ 5]  / answers: 1 / hits: 44066  / 14 Years ago, wed, july 28, 2010, 12:00:00

If I return some value or object in constructor function, what will the var get?



function MyConstroctor()
{
//what in case when return 5;
//what in case when return someObject;
}

var n = new MyConstroctor();


what n will get in both cases?



Actually its a quiz question, what will be the answer?

What is returned from a custom object constructor?

a)The newly-instantiated object

b)undefined - constructors do not return values

c)Whatever is the return statement

d)Whatever is the return statement; the newly-instantiated object if no return statement


More From » javascript

 Answers
29

I found this great link:


JavaScript: Constructor Return Value



The second piece of magic eluded to above is the ability for a
constructor to return a specific, possibly pre-existing object, rather
than a reference to a new instance. This would allow you to manage the
number of actual instances yourself if needed; possibly for reasons of
limited resources or whatnot.





var g_deebee = new Deebee();
function Deebee() { return g_deebee; }
var db1 = new Deebee();
var db2 = new Deebee();
if (db1 != db2)
throw Error(JS constructor returned wrong object!);
else console.log('Equal');




[#96094] Saturday, July 24, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tobyl

Total Points: 598
Total Questions: 110
Total Answers: 114

Location: Vietnam
Member since Sat, Feb 12, 2022
2 Years ago
tobyl questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
;