jsInterface
OOP interface implementation
Definitions
- Interface - entity, declares methods which Implementations must provide.
- Implementation - entity, provides functional for methods declared by Interface.
Main ideas
- To be convinient with Duck typing - check methods existance only when called, and not when Interface or Implementation created / defined.
- Bind context of methods to Interface maintainer - Object with property contained Interface.
Quick intro
Just a simple basic example. You can find usage instructions below it.
// creating Interface declares `.say(..)` and `.greet(..)` methodsconst Speaking = 'say''bye'; // Implementation with `.say(msg)` methodconst speakEnglish = { return ` says: `; };const Duck = name:'Donald'; // Object maintainer for our Interface; // Duck.speak Interface propertyDuckspeak; // ReferenceError: no Implementation yetDuckspeak = speakEnglish; // pointing Implementation to InterfaceDuckspeak; // -> Donald says: hello // another Implementation with extra methodconst speakRussian say: functionmsg return `$this.name говорит: $msg`; } { return ` здоровается!`; }};Duckspeak = speakRussian; // changing ImplementationDuckspeak; // -> Donald говорит: helloDuckspeak; // TypeError: `.greet(..)` is not declared in `Speaking`Duckspeak // ReferenceError: `.bye(..)` is not defined in `speakRussian`
Install
jsInterface avilable on npmjs
npm install --save js-interface
const jsInterface = ;
Usage
-
Creating new jsInterface
You can declare one or list of methods:
const Speaking = 'say';const Speaking = 'say''greet';Or define default Implementation - all of it's methods will be declared in Interface:
const Speaking = // as simple Object{return ` says: `;}{return ` greets everybody!`;};const Speaking = { // as Constructor / Classthis{return ` says: `;}this{return ` greets everybody!`;}}; -
Defining the property with Interface.
You can define the property of simple object
const Duck = {};;or
this
in constructor{;};const Duck = ;in both of this examples
Duck.speak
property will contain Interface; -
Pointing the Implementation
Implementation must be an object or Constructor.
To point the implementation for interface - assign it:
cosnt speakEnglish ={return ` says: `;}{return ` greets everybody!`;};Duckspeak = speakEnglish;You can reassign implementations to change Interface methods behavior. You should assign implementation at least once, if default implementation was not defined.
Declared methods checks at calling only, and not in assignment. Every extra methods will be skiped.