Object inheritance using Object.create() without a constructor function.

Just a quick example of creating an Object inheritance chain using prototype and Object.create() without constructor function (using init()).

by sym3tri

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<div id="result"></div>

JavaScript

var AppError,
  UndefinedReferenceError;

function format(formatString) {
  var args = _.toArray(arguments),
    substitutions = _.rest(args, 1),
    result = _.clone(formatString);
  _.each(substitutions, function (substitution, idx) {
    result = result.replace(new RegExp('\\{' + idx + '\\}', 'g'),
    substitutions[idx]);
  });
  return result;
}

AppError = Object.create(Error.prototype, {
    name: { value: 'AppError' },
    message: { value: 'An unknown error occurred.' },
    // Factory method on the base class... takes a base object and any args
    create: { value: function (BaseObj) {
        var args = _.rest(_.toArray(arguments), 1),
            obj,
            formatArgs;
        if (typeof BaseObj.create === 'function') {
            obj = BaseObj.create(args);
        } else {
            obj = Object.create(BaseObj);
        }
        Object.freeze(obj);
        return obj;
    }}
});

UndefinedReferenceError = Object.create(AppError, {
    name: { value: 'UndefinedReferenceError' },
    message: { value: 'The value of [{0}] is undefined.' },
    // optional create() function the child classes can do any necessary init work
    create: { value: function () {
        var args = _.toArray(arguments),
            obj = Object.create(this);
        if (args.length) {
            formatArgs = [obj.message].concat(args);
            obj.message = format.apply(format, formatArgs);
        }
        Object.freeze(obj);
        return obj;
    }}
});

jQuery(function () {
    try {
        var error;
        // instance version with args
        error = UndefinedReferenceError.create('instanceCreated');
        // instace version with no args
        error = UndefinedReferenceError;
        // factory version with args
        error = AppError.create(UndefinedReferenceError, 'factoryCrated');
        // factory version with no args
        error = AppError.create(UndefinedReferenceError);

        throw error;
        
    } catch(e) {
     ...