coure2011 coure2011 - 2 years ago 88
Javascript Question

What is returned from a constructor?

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

Answer Source

i found this great link : Dead link

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!");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download