2013-01-13 27 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