您可以使用Function.prototype.call.bind
創建一個方法的功能版本。這被稱爲「不安全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;
};
}
什麼是'pop'在這裏?它不是在你的代碼中的任何地方定義的 – zerkms
'[1,2,3,4] .pop() - > 4' – beoliver