Skip to content Skip to sidebar Skip to footer

Javascript Add Dynamic Function To An Object

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 (ar

Solution 1:

Yes:

var functionName = "sayHello";

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

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

Solution 2:

You could use the array format for this:

object[$functionName] = function () {}

Post a Comment for "Javascript Add Dynamic Function To An Object"