How to Pass Javascript Functions Without Them Firing

February 10, 2014

In Javascript, functions are first-class citizens.

Implications?

This means you can pass functions around in Javascript like they were variables. Here’s some example code to illustrate the concept.

//setup prototype

function FunctionObjectProps() {
  this.function_call = null;
}

function msg_alert(msg) {
  alert(msg + 'love');
}

function init_msg_alert(fobj, func_name) {
  fobj.function_call = func_name;
}

$(document).ready(function() {
  var fop = new FunctionObjectProps();
  init_msg_alert(fop, msg_alert);
  fop.function_call('hello');
});

In this code, I’m setting up a prototype. One property of the prototype is that I want it to be able to have a property that stores a function so that I can call that function when needed. I’ve defined this property as function_call.

In the $(document).ready piece of code, I’m initializing an instance of FunctionObjectProps with a property that stores a reference to the msg_alert function.

Why can’t you pass in msg_alert with parentheses?

As it turns out, if I tried to pass in msg_alert by calling init_msg_alert(fop,msg_alert("someday")), I would get an alert box showing "someday love". If you pass in a function with parentheses, you end up calling the function and then you can't execute fop.function_call("hello") due to an "Uncaught TypeError: Property ‘function_call’ of object # is not a function" error. It’s just something you have to be careful of late at night if you’re new to Javascript.

Why would you want to pass around functions as parameters?

For my particular use case, I wanted to pass a function (let’s call it funcA) as a parameter so I could store it in a prototype instance (let's call it prototype_A) as a property (let’s call it prototype_A.function_call), similar to how I stored it in fop.function_call. I then used this instance and its associated property as an input to Javascript's addEventListener method, so I could trigger the function stored in prototypeA.function_call when a click event occurred.

You can see it in the create_button method in the js_dynamic_quiz.js here on Github.


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.