mimic-fn
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
"mimic-fn" is a powerful JavaScript utility that enables one function to mimic another. This becomes especially useful when you are wrapping a function inside another function but still want to preserve the original's name and properties. By using "mimic-fn", the 'mimic' function adopts the name, displayName, and any other properties of the 'source' function. The 'length' property will not be copied, however, prototype, class, and inherited properties are copied. The ‘toString()’ method on the ‘mimic’ function will return the same result as calling the same method on the ‘source’ function, with a comment “Wrapped with to()” prepended. Note that non-configurable properties may be skipped to avoid errors.
The usage of "mimic-fn" is quite straightforward. It can be installed with npm using the command npm install mimic-fn
. Once installed, you can import it into your project using ES6 imports syntax: import mimicFunction from 'mimic-fn';
. This package essentially takes two parameters, a 'mimic' function (that will adopt properties), and a 'source' function (from which properties will be borrowed).
Below is an example of how you would use "mimic-fn" in your code:
import mimicFunction from 'mimic-fn';
function foo() {}
foo.unicorn = '🦄';
function wrapper() {
return foo();
}
console.log(wrapper.name); //=> 'wrapper'
mimicFunction(wrapper, foo);
console.log(wrapper.name); //=> 'foo'
console.log(wrapper.unicorn); //=> '🦄'
console.log(String(wrapper));
//=> '/* Wrapped with wrapper() */\nfunction foo() {}'
The stringified 'wrapper' function shows the true function body of 'foo', demonstrating the 'wrapper' function's successful mimic of 'foo'.
You can find the documentation for "mimic-fn" on the official GitHub page. The README file available here provides a comprehensive guide on how to install, use, and understand what "mimic-fn" does. For more advanced usage, such as option properties for selective property copying, you can refer to the API section of the README.