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 Exception,
UndefinedReferenceException;
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;
}
Exception = {
'name': 'Exception',
'message': 'An unknown exception occurred.',
toString: function () {
return format('{0}: {1}', this.name, this.message);
}
};
UndefinedReferenceException = Object.create(Exception,
{
'name': {
value: 'UndefinedReferenceException'
},
'message': {
value: 'The value of [{0}] is undefined.'
},
'create': { value: function () {
var args = _.toArray(arguments),
formatArgs,
newObj;
newObj = Object.create(this);
if (arguments.length) {
formatArgs = [this.message].concat(args);
newObj.message = format.apply(format, formatArgs)
}
return newObj;
}}
});
jQuery(function () {
try {
throw UndefinedReferenceException.create('factory foobar');
} catch(e) {
jQuery('#result').html(e.toString());
}
});