You have the option to utilize Lodash
Indeed, Lodash offers the specific function you are seeking, it's known as _.invoke
. In the scenario mentioned earlier, you can implement it like this:
const fullName = _.invoke(person, "getFullName", "-");
And it will perform as expected. So, how does _.invoke
function?
- The signature of
_.invoke
is: _.invoke(object, path, [args])
. It triggers the method at the specified path (which could be a nested path or just the method name) within the object, with binding to the object for this
.
Can I experiment quickly in the browser?
Certainly! I have set up a Codepen where you can directly test this and other methods to achieve the same outcome straight from your browser. Just ensure to access the browser console to view the test outcomes! Here is the link, look for _.invoke
in testcase1a()
and testcase1b()
:
https://codepen.io/jhack_jos/pen/ExNVbWp
How is the expression resolved above?
- If
person
is undefined or doesn't contain a method named getFullName
, then the expression _.invoke(person, "getFullName", "-");
resolves in this manner:
//STEP 1
const fullName = _.invoke(person, "getFullName", "-");
//STEP 2
const fullName = undefined;
- If
person
is defined and has the method getFullName
:
//STEP 1
const fullName = _.invoke(person, "getFullName", "-");
//STEP 2
const fullName = person.getFullName("-");
//STEP 3
const fullName = "surname-firstname";
Warning
If person
possesses a property that is not a method named getFullName
, you'll encounter a runtime error!!