在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
出于某种原因,当我做myfunc.length我一直得到0! – qodeninja
@qodeninja:你的问题中的函数没有声明参数,所以'length'确实是'0'。 –
@ T.J.Crowder所以你必须声明你的论点,你不能有一个可变长度? – qodeninja