Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Created August 2, 2013 09:20
Show Gist options
  • Save tobiashm/6138588 to your computer and use it in GitHub Desktop.
Save tobiashm/6138588 to your computer and use it in GitHub Desktop.
Helper function to ensure correct context in JavaScript constructor. Alternative to `function Foo(...) { if (!(this instanceof Foo)) return new Foo(...); ... }`
Function.prototype.make = function(self, args) {
if (self instanceof args.callee) return self;
var F = function() {};
F.prototype = args.callee.prototype;
var o = new F();
F.prototype.constructor.apply(o, Array.prototype.slice.apply(args));
return o;
};
function Foo(name) {
var foo = Foo.make(this, arguments);
foo.name = name;
return foo;
}
var bar = new Foo('john');
var baz = Foo('paul');
console.log('bar is Foo => ' + (bar instanceof Foo));
console.log('baz is Foo => ' + (baz instanceof Foo));
console.log('bar.name => ' + bar.name);
console.log('baz.name => ' + baz.name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment