[OpenLayers-Dev] Patch: fix argument handling in Function.bind()

Andy Armstrong andy at hexten.net
Thu May 17 20:36:29 EDT 2007


The implementation of Function.bind() in BaseTypes.js has a problem in
the case where you supply additional arguments to the bound function
when invoking it.

   Function.prototype.bind = function() {
     var __method = this, args = [], object = arguments[0];
     for (var i = 1; i < arguments.length; i++)
       args.push(arguments[i]);
     return function(moreargs) {
       for (var i = 0; i < arguments.length; i++)
         args.push(arguments[i]);
       return __method.apply(object, args);
     }
   };

Because the args array is captured by the closure any additional
arguments accumulate. So the first call works correctly and then the
second call is made with the arguments from both the first and the
second call - and so on.

This patch fixes it at the expense of an extra array copy. An
alternative would be to truncate the args array to its original length
before returning from the closure. That'd be more efficient but wouldn't
do the right thing if the bound function was re-entrant.

   --- lib/OpenLayers/BaseTypes.js.orig    2007-05-18  
01:25:23.000000000 +0100
   +++ lib/OpenLayers/BaseTypes.js 2007-05-18 01:27:04.000000000 +0100
   @@ -925,9 +925,12 @@
      for (var i = 1; i < arguments.length; i++)
        args.push(arguments[i]);
      return function(moreargs) {
   -    for (var i = 0; i < arguments.length; i++)
   -      args.push(arguments[i]);
   -    return __method.apply(object, args);
   +    var my_args = [], i;
   +    for (i = 0; i < args.length; i++)
   +      my_args.push(args[i]);
   +    for (i = 0; i < arguments.length; i++)
   +      my_args.push(arguments[i]);
   +    return __method.apply(object, my_args);
      }
    };

-- 
Andy Armstrong, hexten.net




More information about the Dev mailing list