0

是否可以使用函数调用来引用方法?

我想我可以尝试这样的事情:

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 x.m() }, lst)
}

var list_a = [ [1,9],[2,8],[3,7],[4,6] ]
var list_b = mapm(pop,list_a)

>Uncaught ReferenceError: pop is not defined 
4

2 回答 2

4

尝试:

mapm( 'pop', list_a )
...
return x[ m ]();

如果你真的想引用函数本身:

mapm( list_a.pop, list_a ); // or Array.prototype.pop
...
return m.apply( x );
于 2012-12-18T01:04:49.823 回答
0

您可以使用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;
  };
}
于 2012-12-18T01:07:50.073 回答