0

Is there any way to add a function to an object without knowing it's name in advance?

I do something like:

var $functionName = "sayHello"; 

object."$functionName" = function (args) {
     // Do stuff 
} 

/// Later

object.sayHello ("Henry");
infused
  • 23,247
  • 13
  • 66
  • 76
rnrneverdies
  • 14,415
  • 9
  • 60
  • 92

2 Answers2

3

Yes:

var functionName = "sayHello";

anObject[functionName] = function (args) {
    // ...
}

Note that a.b is syntactic sugar for a["b"] -- they mean exactly the same thing.

cdhowie
  • 144,362
  • 22
  • 272
  • 285
1

You could use the array format for this:

object[$functionName] = function () {}

Cjmarkham
  • 9,057
  • 4
  • 47
  • 80