JavaScript - bound functions

- 1 min

A quick post to share something I came across last night while tinkering with some JavaScript for a utility I created.

I was creating a number of functions that would later been called on certain events. Each of these functions was essentially the same, but was dependent upon the value of certain variables at the time they were initialised.

My first attempt looked something like this:

View on JSFiddle

When I ran it I expected to see the numbers 0,1,2,3,4 printed, however I got this output:

Function says: 5
Function says: 5
Function says: 5
Function says: 5
Function says: 5

Which makes sense when you think about it (the global variable j has value of 5 after the array is initialised), but this was definitely not what I wanted.

In order to get the result I wanted, I needed to create a bound function, which is associated with the state of j at the time it is added to the array. My next attempt, inspired by the documentation at MDN was as follows:

View on JSFiddle

The output is now:

Function says: 0
Function says: 1
Function says: 2
Function says: 3
Function says: 4

I also realised this could be achieved using a closure, as follows:

View on JSFiddle

This also gives the output:

Function says: 0
Function says: 1
Function says: 2
Function says: 3
Function says: 4

I think this code is a bit neater.

Nothing groundbreaking here, but it gave me an interesting insight into what happens when you start passing functions around. In particular functions that refer to mutable state.

Andrew Myers

Andrew Myers

Web Developer

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin google pinterest medium vimeo