Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Created October 12, 2012 09:01
Show Gist options
  • Save abozhilov/3878192 to your computer and use it in GitHub Desktop.
Save abozhilov/3878192 to your computer and use it in GitHub Desktop.
ctor
function ctor(fn) {
function F () {
var obj = Object.create(F.prototype);
fn.apply(obj, arguments);
return obj;
}
F.prototype = Object.create(fn.prototype);
return F;
}
//Example
var Foo = ctor(function (a, b, c) {
this.a = a;
this.b = b;
this.c = c;
});
Foo.prototype.sum = function () {
return this.a + this.b + this.c;
};
var foo = Foo(1, 2, 3);
console.log(foo.sum()); //6
// Calling the constructor with
// pre-alocated arguments in array.
var args = [1, 2, 3];
var foo1 = Foo.apply(null, args);
console.log(foo1.sum()); //6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment