Skip to content

Instantly share code, notes, and snippets.

@npup
Created September 3, 2010 10:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npup/563727 to your computer and use it in GitHub Desktop.
Save npup/563727 to your computer and use it in GitHub Desktop.
Exploring some ways of fixing when ppl call a constructor function and forgetting a needed "new" operator.
(function (global, ns) {
// Awesome model
function Apa(name, dryg) {
// try to fix if "new" wasn't used
if (!(this instanceof arguments.callee)) {
console.log('No "new" operator used when creating Apa "%s". Fixing..', name);
// v1
//return newFix1(arguments);
// v2
return newFix2(arguments);
}
// validate arguments (of course fails when invoked via function newFix1)
if (typeof name!=='string' || !name) {throw new Error(this.constructor.name+' must be initialized with a name (non empty string)');}
// set props
this.name = name;
this.dryg = !!dryg;
// 2 ways of building an object when "new" was forgotten
function newFix1(args) {
var instance = new args.callee(); // though this call will fail because of the argument validation
args.callee.apply(instance, args);
return instance;
}
function newFix2(args) {
return (function (a,b,c,d,e,f,g,h,i,j) { // XXX: obviously a hack (handles max 10 passed arguments), just to be able to send arguments to the constructor
return new this(a,b,c,d,e,f,g,h,i,j);
}).apply(args.callee, args);
}
}
Apa.prototype.toString = function () {
return (this.dryg?'dryg apa ':'apa ej dryg')+' : '+this.name+'';
};
// Exported API
global[ns] = {
test: function (name, dryg) {
console.log('-----');
// create with/without "new" and debug them
console.log('==> %s', (new Apa(name+'[new]', dryg)).toString());
console.log('==> %s', Apa(name+'[no new]', dryg).toString());
}
};
})(this, 'Apa');
this.Apa.test('Ola', true);
this.Apa.test('Birger', false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment