【问题标题】:how to reference a method javascript?如何引用方法javascript?
【发布时间】:2012-12-18 01:02:10
【问题描述】:

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

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

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 

【问题讨论】:

  • 这里的pop 是什么?它没有在您的代码中的任何地方定义

标签: javascript function methods


【解决方案1】:

试试:

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

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

mapm( list_a.pop, list_a ); // or Array.prototype.pop
...
return m.apply( x );

【讨论】:

    【解决方案2】:

    您可以使用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;
      };
    }
    

    【讨论】:

    • bind 在没有声明的情况下使用是不安全的
    • 当然可以,如果您在 ES5 环境中 - 换句话说,自 2010 年以来制造的任何浏览器。并不是每个人都必须支持 IE8。
    • 但有足够多的人这样做,您不应该在没有“这在 IE8 中不起作用”免责声明的情况下放弃解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2015-05-08
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    相关资源
    最近更新 更多