3

I have a model and want to declare functions for all attributes on it.

Let's say these are the attributes: [firstName, lastName]

I want to be able to get them with:

person.firstName()
person.lastName()

How do I define methods programmatically from an array of strings?

2
  • Is person a singleton or do you have multiple such objects? Commented Nov 27, 2011 at 3:53
  • I have multiple persons. Commented Nov 27, 2011 at 4:19

1 Answer 1

3
['firstName', 'lastName'].forEach(function(funcName) {
    var prop = person[funcName];    
    person[funcName] = function() {
        return prop;
    }
});

CodePad.

If you didn't know the properties in advance, you could use Object.keys() if the environment supports it, or use a for ( in ) loop to get the keys.

CodePad.

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

1 Comment

I don't know the properties in advance so your second solution fits. Really great answer, thanks!

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.