Created
March 6, 2012 16:06
-
-
Save abozhilov/1987066 to your computer and use it in GitHub Desktop.
applyNew
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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