2012-12-18 19 views
0

是否可以使用函數調用來引用方法?如何引用一個javascript方法?

我想我可以嘗試這樣的事:

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 
+0

什麼是'pop'在這裏?它不是在你的代碼中的任何地方定義的 – zerkms

+0

'[1,2,3,4] .pop() - > 4' – beoliver

回答

4

嘗試:

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

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

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

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

'綁定'是不安全的使用而不聲明它 –

+0

當然,如果你在ES5環境 - 換句話說,自2010年以來製作的任何瀏覽器。並非每個人都必須支持IE8。 –

+0

但足夠的人這樣做,你不應該扔掉解決方案沒有「這不適用於IE8」免責聲明 –

相關問題