Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare methods dynamically in Javascript

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?

like image 858
ajsie Avatar asked Jul 25 '26 03:07

ajsie


1 Answers

['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.

like image 62
alex Avatar answered Jul 27 '26 17:07

alex