您可以使用Function.prototype.call.bind
创建方法的功能版本。这被称为“uncurrying this
”。
function map(f, lst) {
// calling map method directly is fine.
return lst.map(f)
}
function mapm(m,lst) {
// where m is a passed method
return map( function(x) { return m(x) }, lst)
}
var pop = Function.prototype.call.bind(Array.prototype.pop);
var list_a = [ [1,9],[2,8],[3,7],[4,6] ]
var list_b = mapm(pop, list_a)
如果您需要它在古代浏览器中工作,您需要填充bind
:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}