遵循jQuery plugin pattern ,在我们使用 apply() 定义 this
和的范围的情况下,如何找到函数的元数,例如 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
最佳答案
您必须使用命名函数表达式 ( with all its idiosyncrasies ):
var methods = {
init : function init () {
var arity = init.length;
}
};
这是 fiddle :http://jsfiddle.net/tqJSK/
说实话,我不知道你为什么需要这个。您可以在函数中对该数字进行硬编码,因为命名参数的数量永远不会改变...
<小时/>更新:正如 @T.J.Crowder 所指出的,您可以使用常规函数声明:
(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;
}
};
这是 fiddle :http://jsfiddle.net/tqJSK/1/
关于javascript - 如何在严格模式下找到匿名函数的元数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14301634/