AutoClass
Define argument types for functions and automatically add methods to prototype.
Installation
npm install autoclass
Example
; const Rider = ; const ShowInfo = ; const dovizioso = ;const iannone = ; dovizioso; // Logs: "Dovi, #4"iannone; // Logs: "The Maniac, #29"
AutoClass(name[, ...type], func)
name: String or Any
A string to use as a method name. If an empty string or not a string, no methods are added.
Type
type: Constructor orZero or more constructors. func
arguments are validated using these corresponding types. Methods are added to prototypes of constructors. Methods are not added to array or variadic types.
func: Function
Function to execute, when instance as function or instance's method is invoked. func
should have equal amount of named arguments as types are declared. func
gets called with formatted and validated (see type) argument values. Its this
value is set to object with argument names of func
as keys and argument instances as values.
Instance
Returns:const MyClass = ;
Type
Three kinds of types can be declared - basic, array and variadic.
const MyClass = ; ; // Logs: "MyClass"
Type conversions
If instanceof
test fails, instance is passed to constructor.
const Rider = ; const dovizioso = ;
If class requires at least two types (variadic type is not considered), constructing from object literal is possible.
// `ShowInfo` requires `Rider`; // Logs: "Petrux, #9"
Values and instances
Function arguments are values. Use this.argumentName
to access instance.
const MyClass = ; const TestType = ; ; // Logs: 123; true
Function and method calls return instance. Use .valueOf()
to access return value.
const MyClass = ; const ref = {}; console; // Logs: true
Create classes
Validate inputs, return value.
const BikeNumber = ; const Rider = ; try ; // Throws: "Error: Bike number must be positive integer, got -36." catch e console; try ; // Throws: "Error: Bike number must be positive integer, got NaN." catch e console;
Method chaining
Functions that return nothing or undefined can be chained.
; ; // Logs: "Stoner, #27" ; // Logs: "Stoner, #1"
Multiple methods from same type
Function may require same type multiple times. Primary method uses instance as first argument of its type. To use instance as another argument of its type, use instance.Method.argumentName(...other args)
.
; // "Hello" as `to` argumentconsole; // Logs: "Hello world!"// "Hello" as `text` argumentconsole; // Logs: " world!Hello"
License
ISC