ciwolsey
ciwolsey

Reputation: 97

Converting strings to methods that output the string

I have an object like this:

options: {
  'Signature': "[Customer First Name] [Customer Last Name]"
  'First Name': "[Customer First Name]"
  'Last Name': "[Customer Last Name]"
}

And I need to convert it so that the values become functions that use that value like this:

options: {
  'Signature': function(){ this.insertHTML('[Customer First Name][Customer Last Name]'); }
  'First Name': function(){ this.insertHTML('[Customer First Name]'); }
  'Last Name': function(){ this.insertHTML('[Customer Last Name]'); }
}

But I'm not sure how to do this. So as an example I want to be able to do something like:

var newOptions = functionify(options);

Upvotes: 0

Views: 35

Answers (2)

GeReV
GeReV

Reputation: 3265

In JavaScript, it's possible to create functions which return functions.

For example:

function functionify(str) {
  return function() {
    return str; // Or whatever you want in your function body.
  };
}

So, by calling functionify and passing some string to it, you'll get in return a function which returns that string:

var fun = functionify('Hello, World!'); // fun is now a function

fun(); // returns "Hello, World!"

This can be applied to keys and values of an object in any of several ways (depending on your preference; a for-in loop, Object.keys to name a couple).

Another example:

obj['key'] = functionify(obj['key']);
obj['key']();

Upvotes: 1

James Allardice
James Allardice

Reputation: 166031

Here's one potential solution. Iterate over the keys of options and build up a new object:

var newOptions = Object.keys(options).reduce(function ( obj, option ) {
  obj[ option ] = function () {
    this.insertHTML(options[ option ]);
  };
  return obj;
}, {});

Note that this inside those functions is unlikely to refer to what you expect it to, unless you're invoking those functions with some other explicit context (e.g. via call or apply).

Upvotes: 2

Related Questions