Created
January 23, 2015 12:27
-
-
Save redism/324d5485af276e07d744 to your computer and use it in GitHub Desktop.
Javascript new with apply
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 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