Binding functions in javascript

Date: 19 Jun 2012
Author: Erik Dubbelboer

A very useful javascript function that not many people seem to know is bind()

bind() allows you to set the this variable a function is executed in. When using a more object oriented approach this can be very useful.

Another thing you can do with bind() is pre assign some of the arguments provided to the function. This can be used to pass additional arguments to your event handlers.

See this simple example:

var http = require('http');

function handleRequest(data, req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('data: ' + data);
}

http.createServer(handleRequest.bind(this, '1337'     )).listen(8081);
http.createServer(handleRequest.bind(this, 'something')).listen(8082);
comments powered by Disqus