Pg-promise: "Inserts" function from the "Performance-Boost" section.

Created on 4 Apr 2016  路  6Comments  路  Source: vitaly-t/pg-promise

In this function:

function Inserts(template, data) {
    if (!(this instanceof Inserts)) {
        return new Inserts(template, data);
    }
    this._rawDBType = true;
    this.formatDBType = function () {
        return data.map(d=>'(' + pgp.as.format(template, d) + ')').join(',');
    };
}

what is the point of this block of code?

if (!(this instanceof Inserts)) {
    return new Inserts(template, data);
}

I've never seen anything like it before.

question

All 6 comments

This is a very standard JavaScript checking how the code was invoked - as a class or as a function.

And if it was invoked as a function, it is automatically translated into a class call that way.

@vitaly-t why not just enforce always using the new keyword instead of doing this?

Enforce? You mean to throw an error? That wouldn't be friendly :)

That code makes it flexible ;) You can use it as a class or as a function ;)

Thank you! I appreciate how well maintained this library is. Finding it, and seeing 0 issues was really reassuring.

n.p. ;)

F.Y.I. Important breaking change in v6.5.0.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

msjoshi picture msjoshi  路  4Comments

Fte-github picture Fte-github  路  4Comments

normanfeltz picture normanfeltz  路  4Comments

leemhenson picture leemhenson  路  5Comments

illarionvk picture illarionvk  路  3Comments