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?
['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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With