Skip to content

Instantly share code, notes, and snippets.

@redism
Created January 23, 2015 12:27
Show Gist options
  • Save redism/324d5485af276e07d744 to your computer and use it in GitHub Desktop.
Save redism/324d5485af276e07d744 to your computer and use it in GitHub Desktop.
Javascript new with apply
var Adder = function Adder() {
console.log(arguments);
this.list = Array.prototype.slice.apply(arguments);
};
Adder.prototype.sum = function sum() {
var sum = 0;
this.list.forEach(function(x) {
sum += x;
});
return sum;
};
var l = new Adder(1,2,3);
console.log(l.sum()); // 6
var numbers = [1,2,3];
l = new (Function.prototype.bind.apply(Adder, numbers));
console.log(l.sum()); // 5 ??
// Correct solution
//
// http://stackoverflow.com/a/1608546/388351
var construct = function construct(constructor, args) {
function F() {
return constructor.apply(this, args);
}
F.prototype = constructor.prototype;
return new F();
};
l = construct(Adder, numbers);
console.log(l.sum()); // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment