Ben
Ben

Reputation: 57207

JS pattern providing function name as string

Lately, I've found myself passing function names as string parameters to another function, checking its existence with typeof, and calling it if necessary.

I realize as I write this that I could just pass a function reference.

My question is, does the "pass function name as a string" pattern have a common name? And, is it an anti-pattern - should I generally be using references whenever possible?

Upvotes: 0

Views: 75

Answers (2)

Greg Burghardt
Greg Burghardt

Reputation: 18783

I don't know of a specifically named pattern, but if you combine this with calling that function via eval then I would say that is the anti pattern.

OK

var obj = {
    foo: function() {},
    bar: function() {},
    execute: function(fnName) {
        this[fnName]();
    }
};

obj.execute("foo");

Bad

var obj = {
    foo: function() {},
    bar: function() {},
    execute: function(fnName) {
        eval("obj." + fnName + "()");
    }
};

Upvotes: 0

Dan Crews
Dan Crews

Reputation: 3597

I don't know that it has a name, but it's definitely an anti-pattern. It's harder, and iirc it's actually going to be worse on memory than just sending the function reference around.

function doThisThing() {}
var action = 'doThisThing';

You see I actually create two things in memory with a pointer to each.

var action = function() {}

Here, I created a single item in memory, and action is just a pointer to it. Then it's super easy to just

if (action) action();

or even shorter

action && action();

It's so so much easier just to pass a reference around. It's just that: a reference. It has little-to-no overhead, and it's way easier.

Upvotes: 2

Related Questions