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
  • 24,000
  • 13
  • 68
  • 78
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95

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
  • 158,093
  • 24
  • 286
  • 300
1

You could use the array format for this:

object[$functionName] = function () {}

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81