extensible-function
An extensible ES6 function with idiomatic inheritance and various other benifits:
Installation
npm install --save extensible-function
- When extending
ExtensibleFunction
, the code is idiomatic of extending any ES6 class (no, mucking about with pretend constructors or proxies). - The prototype chain is retained through all subclasses, and
instanceof
/.constructor
return the expected values. .bind()
.apply()
and.call()
all function as expected. This is done by overriding these methods to alter the context of the "inner" function as opposed to theExtensibleFunction
(or it's subclass') instance..bind()
returns a new instance of the functions constructor (be itExtensibleFunction
or a subclass). It usesObject.assign()
to ensure the properties stored on the bound function are consistent with those of the originating function.- Closures are honored, and arrow functions continue to maintain the proper context.
- The "inner" function is stored via a
Symbol
, which is obfuscated by the module.
ExtensibleFunction
ExtensibleFunction
Example of extending const ExtensibleFunction = ;// OR //; // Lets extend our `ExtensibleFunction` into an `ExtendedFunction` { // Just use `super()` like any other class // You don't need to pass ...args here, but if you used them // in the super class, you might want to. superfn ...args; // Just use `this` like any other class. No more messing with fake return values! let constructedPropertyValue ...rest = args; thisconstructedProperty = constructedPropertyValue; }
ExtendedFunction
Example of using the let fn = { // Add `this.y` to `x` // If either value isn't a number, coax it to one, else it's `0` return thisy>>0 + x>>0} "I'm a constructed property value"; fnadditionalProperty = "I'm an additional property value";
This is what you get
fn instanceof Function; // truefn instanceof ExtensibleFunction; //truefn instanceof ExtendedFunction; //truefn instanceof Function; //truefn instanceof ExtensibleFunction; //truefn instanceof ExtendedFunction; //truefnconstructor == ExtendedFunction; //truefnconstructedProperty == "I'm a constructed property value"; //truefnadditionalProperty == "I'm an additional property value"; //truefnconstructedProperty == fnconstructedProperty; //truefnadditionalProperty == fnadditionalProperty; //true == 0; //true == 10; //truefn == 20; //truefn == 30; //truefn10 == 40; //true
ExtensibleFunction.Bound
The module also provides a convenient constructor which binds a function to itself. Yeah, it sounds weird but the benefit is that calls to these functions have their this
set to themselves.
Example of using ExtensibleFunction.Bound
Bound { superfn; thisx = x; } let bfn = { return thisx + y;} 100; ; // 142bfnx = 0;; // 42