Javascript syntax of "a= object,object"

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!

Upvotes: 2

Views: 471

Answers (2)

sth
sth

Reputation: 229603

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;
}

Upvotes: 7

Christoph
Christoph

Reputation: 169593

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!

Upvotes: 3

Related Questions