javascript: Why can some functions be bound and mapped and others not? -
out of curiosity:
the mdn taught me how shortcut function application this:
trim = function.prototype.call.bind(string.prototype.trim) join = function.prototype.call.bind(array.prototype.join)
now, can map trim
, not join
reason. join
takes ','
default argument (separator), should fine, instead uses array index:
> trim = function.prototype.call.bind(string.prototype.trim) call() > [' a','b '].map(trim) ["a", "b"] > join = function.prototype.call.bind(array.prototype.join) call() > [['a','b'],['c','d']].map(join) ["a0b", "c1d"]
why?
also, if wanted different separator? passing bind
doesn't work, since prepended existing arguments (at time 1 of elements of list on map). takes role of strings join , strings join act separators if there separate:
> joins = function.prototype.call.bind(array.prototype.join,';') call() > [['a','b'],['c','d']].map(joins) [";", ";"]
i have researched , found:
answers explaining thing this
, solutions equivalent bind
shortcut referenced
similar explanations, solution using thisarg
again, mdn's page map
the function pass map receives 3 arguments. map works this.
array.prototype.map = function(f) { var result = []; for(var = 0; < this.length; i++) { result.push(f(this[i], i, this)); } return result; }
so when run code [['a','b'],['c','d']].map(join)
, what's happening inside map
join(['a', 'b'], 0, [['a','b'],['c','d']]) join(['c', 'd'], 1, [['a','b'],['c','d']])
to result want write function can generate join functions. e.g.
function joinsep(separator) { return function(array) { return array.join(separator) } } var joins = joinsep(';'); [['a','b'],['c','d']].map(joins)
Comments
Post a Comment