2

Yesterday I found this function:

function clone(obj) {
    return typeof obj === 'undefined' ?
        this : (clone.prototype = Object(obj), new clone);
}

I though that i saw alot in Javascript, but this syntax is unknown for me:

 clone.prototype = Object(obj), new clone

Can someone explain me how to read this?? Can you give me link to proper definition ? I couldn't find it in Mozilla's MDC, and dont know how to find this on web, but this is first time ever I saw that syntax. Thanks for effort here.

Final solution:

I did some testing according to answers here and there is what I found:

var b;
b=alert('test'),6;
alert(b);  // alert undefined
b=5,alert('test2');
alert(b);  // alert 5

Thanks to christoph research we found more:

var a, b, c;
a = 1, 2;   // a is 1
(b = 1), 2; // b is 1 - same as above!
c = (1, 2); // c is 2

Ahh and I tested it also on IE6 and it works, so this have to be realy old syntax and there is no information about it? :( Strange...

Both of you guys gave good solution, thanks for solution here!

  • 1
    Section 11.14 in http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf Try: alert((1,2,3,4)); – some Jan 25 '09 at 05:34

2 Answers2

7

Comma operator at MDC:

The comma operator (,) simply evaluates both of its operands and returns the value of the second operand.

In this case it does work like calling this function:

function() {
   clone.prototype = Object(obj);
   return new clone;
}
Barry Kaye
  • 7,682
  • 6
  • 42
  • 64
sth
  • 222,467
  • 53
  • 283
  • 367
3

Your 'final solution' gives unexpected results because of operator precedence. The following example might help to clarify the issue:

var a, b, c;
a = 1, 2;   // a is 1
(b = 1), 2; // b is 1 - same as above!
c = (1, 2); // c is 2

Also notice that

var a = 1, 2;

produces a syntax error!

Christoph
  • 164,997
  • 36
  • 182
  • 240