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

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

@sth: This is almost what I wanted to hear, but mine research gives me a little diffrent result (see Final solution revision)
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!

1 Comment

Yes I noticed that "var a" and simple a does not. Thats very interesting syntax here. Nice catch with bracers there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.