在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