Lodash _.functions Method Explained
The _.functions method in the Lodash JavaScript library
inspects an object and extracts an array containing the names of all its
own enumerable function properties. This article explains how
_.functions operates, what specific data it retrieves, how
it filters object properties, and how it differs from similar Lodash
methods.
What _.functions Extracts
The _.functions method (also aliased as
_.methods) iterates through an object and returns an array
of string keys representing properties whose values are functions.
Specifically, the method extracts:
- Only function property names: Any property holding a primitive value (such as a string, number, or boolean) or a standard object is ignored.
- Only own properties: It exclusively inspects properties defined directly on the target object, omitting any methods inherited through the prototype chain.
- Only enumerable properties: Non-enumerable methods
defined via mechanisms like
Object.defineProperty()withenumerable: falseare excluded.
The returned array contains the property names (keys) as strings, sorted in ascending alphabetical order, rather than the function implementations themselves.
Code Example
const _ = require('lodash');
function CustomService() {
this.start = function() { return 'started'; };
this.stop = function() { return 'stopped'; };
this.status = 'active'; // Non-function property
}
// Inherited prototype method
CustomService.prototype.restart = function() { return 'restarted'; };
const service = new CustomService();
const result = _.functions(service);
console.log(result);
// Output: ['start', 'stop']In this example, _.functions extracts
['start', 'stop']. It ignores the string property
status because it is not a function, and it ignores
restart because it belongs to the prototype chain rather
than the instance itself.
_.functions vs. _.functionsIn
Lodash provides a companion method called _.functionsIn.
The key distinction lies in inheritance:
_.functions(object): Extracts function names only from the object’s own properties._.functionsIn(object): Extracts function names from both own and inherited enumerable properties across the entire prototype chain.
Using _.functionsIn(service) on the previous example
would yield ['restart', 'start', 'stop'].
Common Use Cases
The _.functions method is primarily used for:
- Introspection and Reflection: Discovering available capabilities and API endpoints on dynamically loaded objects or modules.
- Auto-binding Context: Identifying methods on an
object to bind their execution context (
this) automatically. - Proxying and Wrapping: Iterating through object methods to apply middleware, logging, or debugging wrappers dynamically.