Created
August 17, 2010 08:21
-
-
Save cms/528942 to your computer and use it in GitHub Desktop.
newApply
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
// newApply: Invoke a consturctor function correctly, passing an arbitrary | |
// number of arguments | |
function newApply(fn, argsArray) { // (c) Christian C. Salvadó - MIT License | |
var F = newApply, obj, ret, t, isPrimitive; | |
if (this instanceof F) return; // this function is used as a dummy constructor | |
F.prototype = fn.prototype; // set up the prototype and constructor properties | |
F.prototype.constructor = fn; | |
obj = new F; // create a new instance using this function as a constructor | |
ret = fn.apply(obj, argsArray); // apply original constructor function | |
t = typeof ret; // get the type of the returned value | |
// check if the returned value is a primitive | |
isPrimitive = (t == "object") ? ret === null : t != "function"; | |
return isPrimitive ? obj : ret; | |
} | |
// Exampe usage: | |
function Foo(a,b,c) { | |
this.a = a; | |
this.b = b; | |
this.c = c; | |
} | |
var args = ['a','b','c']; | |
var obj = newApply(Foo, args); | |
console.log( | |
obj instanceof Foo, // true | |
Foo.prototype.isPrototypeOf(obj), // true | |
obj.a === 'a', // true | |
obj.b === 'b', // true | |
obj.c === 'c' // true | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment