Given I have this code:
if (_.isFunction(this.doSomething)) {
this.doSomething();
}
Whereby loadingComplete is a directive attribute passed in from a parent controller that may not always be provided, is there a cleaner one-line way to call the method if it exists, without repeating the method name?
Something like:
_.call(this, 'doSomething');
_.result(this, 'doSomething', 'defaultValueIfNotFunction')
As of version 4.0.0 lodash provides a method called invoke
: https://lodash.com/docs/4.15.0#invoke
var object = {
add: function(a, b) { return a + b }
};
_.invoke(object, 'add', 1, 2);
// => 3
_.invoke(object, 'oops');
// => undefined
Note that it will still explode if for some reason there is something other than a function at the key you provide.
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