CustomError Inherit with Object.setPrototypeOf() vs CustomError Inherit with Object.create()

Edit on GitHub

Performance test for CustomError that inherits Error via Object.setPrototypeOf() vs Object.create()

Setup

function CustomError(message) {
    Object.defineProperty(this, 'name', {
        enumerable: false,
        writable: false,
        value: 'CustomError'
    });

    Object.defineProperty(this, 'message', {
        enumerable: false,
        writable: true,
        value: message
    });

    if (Error.hasOwnProperty('captureStackTrace')) { // V8
        Error.captureStackTrace(this, this.constructor);
    } else {
        Object.defineProperty(this, 'stack', {
            enumerable: false,
            writable: false,
            value: (new Error(message)).stack
        });
    }
}

Tests

  • CustomError Inherit with Object.setPrototypeOf()

    Object.setPrototypeOf(CustomError, Error.prototype);
    
    var e = new CustomError('test error');
    console.log(e.message, e instanceof Error, e instanceof CustomError);
  • CustomError Inherit with Object.create()

    CustomError.prototype = Object.create(Error.prototype);
    
    var e = new CustomError('test error');
    console.log(e.message, e instanceof Error, e instanceof CustomError);