Skip to content

another guard against omitting the new keyword #342

Description

@lewisje

This is well-known but may also be considered an antipattern, especially because it cannot be encapsulated, and instead the constructor name must be updated in three places, and the argument list in two, if either is changed, all because Function#apply cannot perform a constructor call:

function Constructor(arg, arg2) {
    if (!(this instanceof Constructor)) {
        return new Constructor(arg, arg2);
    }
    // rest of constructor code
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions