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");
1
  • Unrelated: Is it a PHP influence to name variables starting with $? Or jQuery? Commented Aug 21, 2014 at 4:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use the array format for this:

object[$functionName] = function () {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.