Question

Following the jQuery plugin pattern, how can one find the arity of a function, say the methods.myfunc function, in the case where we've used apply() to define the scope of this and applying arguments to this?

(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" );
  }

}...

This may expose some of my ignorance with function scope, but I'm pretty stumped here, and have not found an example that explains this well enough.

Part of my inspiration for this question comes from NodeJS/ExpressJS, where they have a variable number of arguments for some functions. If 3 arguments are passed, for example, it's assumed there is an error object, but you could just as easily pass two and there's no problem!

update: changed function in code from init to myfunc

Was it helpful?

Solution

You'll have to use a named function expression (with all its idiosyncrasies):

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

Here's the fiddle: http://jsfiddle.net/tqJSK/

To be honest though, I have no idea why you'd ever need this. You can hard code that number within the function, since the amount of named arguments will never change...


Update: as pointed out by @T.J.Crowder, you can use regular function declarations instead:

(function($, window, document) {

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

    var methods = {
      init : init
    };

}(jQuery, window, document));

Update 2: if all you're looking for is the number of arguments supplied in this specific call, just use arguments.length:

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

Here's the fiddle: http://jsfiddle.net/tqJSK/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top