javascript functional programming question. here screen-scrape of node repl session. why y(4) call not push x array? there simpler way function near bottom same thing?
> var x = [] undefined > var y = x.push undefined > x.push(3) 1 > y(4) 2 > x [ 3 ] > y.call(4) undefined > x [ 3 ] > (function(data){x.push(data);})(4) # typing :-) undefined > x [ 3, 4 ] please forgive if duplicate question; it's not clear me how search kind of thing.
the first parameter .call this context used inside function. believe work if use instead:
y.call(x, 4) when don't set this properly, not acting on x. when create reference y x.push, reference not bound x. if want bound version of push, can use var y = x.push.bind(x) suggested @go-oleg (or array.prototype.push.bind(x)). y(4) push x.
now, problem array.prototype.push relies on this, being more suited object-oriented programming style. more functional approach, believe, following (illustrated underscore library):
function push(arr) { return arr.push.apply(arr, _.rest(arguments)); } var x = []; var pushtox = _.partial(push, x); pushtox('foo', 'bar'); console.log(x); // ['foo', 'bar']
Comments
Post a Comment