Last Updated: February 25, 2016
· rwz

JavaScript/CoffeeScript binding techniques for different environments

Suppose you want to do something similar to this:

# won't work, context is lost here
  url: '/foo',
  success: myObj.myMethod

Client with jQuery:

success: $.proxy(myObj, 'myMethod')

Client with underscore:

success: _.bind(myObj.myMethod, myObj)

Node.js or client with newer browser:

success: myObj.myMethod.bind(myObj)

Vanilla JS, any browser:

success: function(){ return myObj.myMethod.apply(myObj, arguments); }


success: -> myObj.myMethod(arguments...)

7 Responses
Add your response


Looks like you want to use => instead of -> here (coffeescript)

over 1 year ago ·

Your vanilla JS is more complicated than you need it to be. If you're going to create a new function and call call myObj.myMethod in it, you don't need to use apply.

over 1 year ago ·

@matthewwithanm apply is the only was to pass all arguments directly to a function. If you know an easier way to do the same thing, please tell (there is none actually).

over 1 year ago ·

@koehr no, => preserve the current context, which is unimportant.

over 1 year ago ·

@rwz Sorry, didn't mean to offend! Yes, obviously apply is the way to forward all possible received arguments, but in this case, you know what arguments the success callback is getting so you can just do a normal invocation with them.

Since the title of the article is "binding techniques for different environments," (and there isn't much in the way of explanation), it's easy for people reading it to assume that "apply" is necessary to manipulate the execution context of the function (which it's often used for) but that's not the case. That's all I was hoping to clarify.

over 1 year ago ·

@matthewwithanm you're absolutely right, in this particular example a much simple code like that could work:

success: function(a1, a2, a3){ return myObj.myMethod(a1, a2, a3); }

but I wanted to make an example with kinda more unified and general way of doing binding where you're not concerned by the number of arguments.

over 1 year ago ·

I thought @koehr was correct that you should use => in the CoffeeScript example, because I assumed the $.ajax block was inside myObj. Great post, but this could be clearer. :)

over 1 year ago ·