2013-01-13 40 views
0

jQuery plugin pattern之後,如果我們使用apply()來定義this的範圍並將arguments應用於此函數,那麼如何找到函數的函數,如methods.myfunc函數?如何在嚴格模式下找到匿名函數的參數?

(function($, window, document){ 

"use strict"; 
//... 
methods = { 
    myfunc: function(){ 
    // myfunc.length? tried, didnt work 
    // arguments.length? tried, didnt work 
    // methods.myfunc.length? tried, didnt work 
    // arguments.callee tried, doesnt work in strict mode 
    } 
    //... 
} 

$.MyPluginThing = function(method){ 

    if(methods[method]){ 
     return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
    }else if(typeof method === "object" || ! method){ 
     return methods.init.apply(this, arguments, window); 
    }else{ 
     $.error("Method " + method + " does not exist on jQuery.MyPluginThing"); 
    } 

}... 

這可能會使一些我的無知與功能範圍,但我敢在這裏難倒,並沒有發現,說明這不夠好例子。

我對這個問題的一些啓發來自NodeJS/ExpressJS,他們在這裏爲某些函數提供了可變數量的參數。例如,如果傳遞3個參數,則假定存在錯誤對象,但您可以輕鬆傳遞兩個參數,這沒有任何問題!

更新:更改的功能代碼由init到MYFUNC

回答

3

你必須使用一個命名函數表達式(with all its idiosyncrasies):

var methods = { 
    init : function init() { 
    var arity = init.length; 
    } 
}; 

這裏的小提琴:http://jsfiddle.net/tqJSK/

說實話,我不知道你爲什麼需要這個。您可以難在函數中的代碼數量,因爲命名參數的數量永遠不會改變......


更新:由@TJCrowder指出的那樣,你可以使用普通的函數聲明改爲:

(function($, window, document) { 

    function init() { 
     var arity = init.length; 
    } 

    var methods = { 
     init : init 
    }; 

}(jQuery, window, document)); 

更新2:如果你正在尋找的是在這個特定呼叫提供參數的個數,只是使用arguments.length

var methods = { 
    init : function() { 
    var count = arguments.length; 
    } 
}; 

這裏的小提琴:http://jsfiddle.net/tqJSK/1/

+0

出於某種原因,當我做myfunc.length我一直得到0! – qodeninja

+1

@qodeninja:你的問題中的函數沒有聲明參數,所以'length'確實是'0'。 –

+0

@ T.J.Crowder所以你必須聲明你的論點,你不能有一個可變長度? – qodeninja