what is this code doing?

72 views
Skip to first unread message

Reza Razavipour

unread,
Sep 11, 2014, 5:41:15 PM9/11/14
to nod...@googlegroups.com


function Param(stringifiedValue) {
    if (!this instanceof Param) {
        return new Param(stringifiedValue);
    }

    this.value = stringifiedValue;
}

Is this only doing away with the user having to do a new?

Can someone explain?

mscdex

unread,
Sep 11, 2014, 8:15:34 PM9/11/14
to nod...@googlegroups.com
On Thursday, September 11, 2014 5:41:15 PM UTC-4, Reza Razavipour wrote:
Is this only doing away with the user having to do a new?

You're correct, although it's usually `if (!(this instanceof Param))` instead of `if (!this instanceof Param)` for clarity.

Aria Stewart

unread,
Sep 12, 2014, 12:01:42 AM9/12/14
to nod...@googlegroups.com
Exactly that.

Ryan Graham

unread,
Sep 12, 2014, 12:02:37 AM9/12/14
to nodejs
That is probably what the author intended, yes.

However, ! has higher precedence than instanceof, so it is actually broken.

It should be "if (!(this instanceof Param))" for the (likely) desired effect.

~Ryan
--
http://twitter.com/rmgraham

Ryan Schmidt

unread,
Sep 12, 2014, 12:02:37 AM9/12/14
to nod...@googlegroups.com
Yes. If a consumer of this code writes "var p = Param()" instead of "var p = new Param()", the above instanceof check will make things still work right. Without that code, "var p = Param()" will silently fail to work in the expected manner.

Some more on this topic:

http://stackoverflow.com/a/383503/951159

Reply all
Reply to author
Forward
0 new messages