开发者

in javascript, is it possible for a NEW function to return NULL?

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 -- null won't do -- although ironically typeof null is also object

function F(x) {
  if (x < 10) return new Number(0);

  this.x = x;
}

now you can do your thing...

for ( var i = 1, k = new F(i); k; k = new F(++i) ) {
  // dance .~.~.~.
}


new F returns an object.

null is a value not an object.

You cannot do this

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜