On Feb 27, 2006, at 10:33 PM, Doug Crawford wrote:

> I am trying to make a function called methodgetter.  This is  
> similar to
> itemgetter but calls an object method rather than returning an object
> property.  For the most part, the following code works:
> function methodgetter(name) {
>     return function(object){ return object[name].call(object); }
> }
>
> But I also want to use map with multiple arguments like so:
> map(methodgetter('aMethod'), objectArray, methodArgumentArray);
>
> I had to modify the closure to look like:
> function methodgetter(name) {
>     return function(object, a){ return object[name].call(object, a); }
> }
>
> I thought it would be possibly to extend this to many arguments by
> using:
> function methodgetter(name) {
>     return function(object){ return object[name].apply(object,
> arguments); }
> }
>
> However, this does not work.  Am I missing something with the use of
> the javascript arguments variable?

First off, your proposed implementation has the wrong semantics.  If  
it worked, your methodcaller("func")(obj, a, b, c) would translate to  
obj.func(obj, a, b, c) instead of obj.func(a, b, c).

If JavaScript were slightly less brain damaged, this would work  
across implementations with the proposed semantics:

methodgetter = function (name) {
        return function (object/*, ... */) {
                return object[name].call.apply(arguments);
        };
};

But of course, in most implementations, call is bastardized and isn't  
really a function (in the sense of Function.prototype) like it should  
be.  What you need is something like this:

methodgetter = function (name) {
        return function (object/*, ...*/) {
                return object[name].apply(object, extend(null, arguments, 1));
        };
};

Which works like this:

 >>> methodgetter("func")
function (object) { return object[name].apply(object, extend(null,  
arguments, 1)); }
 >>> f = {toString: function () {return "f"}, func: function ()  
{ return concat([this], arguments); }};
f
 >>> methodgetter("func")(f)
[f]
 >>> methodgetter("func")(f, 1, 2, 3)
[f, 1, 2, 3]

Since you specifically probably want something pure, here's what that  
translates to sans MochiKit:

methodgetter = function (name) {
        return function (object/*, ... */) {
                var args = [];
                for (var i = 1; i < arguments.length; i++) {
                        args.push(arguments[i]);
                }
                return object[name].apply(object, args);
        };
};

-bob


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"MochiKit" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/mochikit
-~----------~----~----~----~------~----~------~--~---

Reply via email to