Quick actions

cmd+k|ctrl+k

Navigation

Languages

Custom new operator

Snippet info

Language

JavaScript

Visibility

public

Author

paulkotov

Created

2021-04-21T20:30:18.270758Z

Updated

2021-05-28T10:23:24.750551Z

function isPrimitive(val) {
    return val !== Object(val);
}

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

function customNew(constructor, args) {

    const self = Object.create({});
    const constructorValue = constructor.apply(self, args) || self;

    return isPrimitive(constructorValue) ? self : constructorValue;
}

const obj = customNew(Person, ['John', 'Doe']);

console.log(obj);
INFO