a function can return null, but is there any way for the new instance of a function to return null?
for example, in this silly code (strictly for purposes of illustration)
var f = function(j) { if( j > 5 ) return null; this.j = j; };
for( var f1=f(1); f1; f1=f(fi.j) ) {
...
}
what the code does not do is have new f() return null – it seems when new the return value is simply being thrown away. here new f() has not guts at all except __proto__, but refuses to nullify itself.
is the reasonable alternative to look for a gutless “object” being returned? if so, not knowing before hand what the “object” supposed to look like, what would be the best way to test for this?
solution:
considering that javascript’s new cannot fail – it must return an object and cannot return null (see answers below!), imho the proper way to accomplish the example:
var F = function(i) { if( i > 5 ) throw( 'tooMuch' ); this.i = i; }
try {
for( var f = new F(1); true; f = new F(f.i) ) {
...
}
} catch( er ) { null; }
this uses throw/catch for loop control – has not been my cup of tea, but the new javascript specs on iterators uses this same mechanism, so I probably need to be thinking to myself “thow exceptions”, not “thow errors”.
ou CAN return your own object instead of the object given by
new— but remember it has to be an object —nullwon’t do — although ironicallytypeof nullis alsoobjectnow you can do your thing…