Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Created March 6, 2012 16:06
Show Gist options
  • Save abozhilov/1987066 to your computer and use it in GitHub Desktop.
Save abozhilov/1987066 to your computer and use it in GitHub Desktop.
applyNew
var PROTO_TYPE = {
'[object String]' : String,
'[object Number]' : Number,
'[object Boolean]' : Boolean
};
function applyNew(f, a) {
var construct = PROTO_TYPE[{}.toString.call(f.prototype)];
if (construct) {
return new construct(a[0]);
}
function F() {
return f.apply(this, a);
};
F.prototype = f.prototype;
return new F;
}
//Example
function Foo(a, b, c, d, e) {
print([
'a: ' + a,
'b: ' + b,
'c: ' + c,
'd: ' + d,
'e: ' + e
].join('\n'));
print(this.method());
}
Foo.prototype.method = function () {
return 'method';
};
var obj = applyNew(Foo, [1, 2, 3, 4, 5]);
print(obj instanceof Foo); //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment