Skip to content

Instantly share code, notes, and snippets.

@cms
Created August 17, 2010 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cms/528942 to your computer and use it in GitHub Desktop.
Save cms/528942 to your computer and use it in GitHub Desktop.
newApply
// 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