Saturday 18 March 2017

bind function in JS without binding 'this' value

Saw we have a simple fn like so:

function run(foo, cb){
   setTimeout(function(){
      cb(null, foo);
   }, 400);
}

and we want to reuse the function, maybe with the async library:

async.map({

foo: run.bind(null,'foo'),
bar: run.bind(null,'bar'),
baz: run.bind(null,'baz')

}, function(err){


});

what I would like to do is avoid binding the "this" value in the function.

One thing we could do is this instead:

   function run(foo){
    return function(cb){
       setTimeout(function(){
          cb(null, foo);
       }, 400);
    }
  }

and then have this:

async.map({

foo: run('foo'),
bar: run('bar'),
baz: run('baz')

}, function(err){


});

this is cleaner, but I think that using the bind functionality can produce more generic code, objectively, over using the latter pattern.

Does anyone know if there is a native way to call bind without binding the "this" value of a function. Or perhaps a way to implement a Function.prototype.bind() function that doesn't bind the "this" value?

Here's my attempt:

Function.prototype.customBind = function(){

    var self = this;
    var args1 = Array.from(arguments);

    return function(){

    var args2 = Array.from(arguments);
    self.apply(this, args1.concat(args2));
   }

};

in this way, we can use the dynamic value for "this"? We would use this code like so:

async.map({

foo: run.bindCustom('foo'),
bar: run.bindCustom('bar'),
baz: run.bindCustom('baz')

}, function(err){


});



via Alexander Mills

No comments:

Post a Comment