-2

I was trying to "put a function into an object" so I wanted to do something like this but I'm getting errors everywhere.

var someobject = {
    makename(1)  : null,
    makename(2)  : null,
    makename(3)  : null,
    makename(4)  : null
};

function makename(num) {
    return (identifier + ' Bot' + num)
}
Dr Goat
  • 21
  • 5

2 Answers2

3
var someobject = {}

someObject[makename(1)] = null;
someObject[makename(2)] = null;
someObject[makename(3)] = null;
someObject[makename(4)] = null;

This works everywhere. However, @pointy's solution is nicer!

lex82
  • 11,173
  • 2
  • 44
  • 69
3

In modern (ES2015) JavaScript environments, you can do this:

var someobject = {
  [makename(1)]: "foo",
  [makename(2)]: "bar"
};

The [ ] wrapper around the property name allows it to be an arbitrary expression. The result of evaluating the expression is interpreted as a string and used as the property name.

Pointy
  • 405,095
  • 59
  • 585
  • 614