method
Library provides an API for defining polymorphic methods that dispatch on the first argument type. This provides a powerful way for decouple abstraction interface definition from an actual implementations per type / instance, without risks of interference with other libraries.
Motivation
- Provide a high-performance, dynamic polymorphism construct as an alternative to existing object methods that does not provides any mechanics for guarding against name conflicts.
- Allow independent extension of types, and implementations of methods on types, by different parties.
Install
npm install method
Use
var method = // Define `isWatchable` method that can be implemented for any type.// Use some UNIQUE identifer for the method to avoid any naming collisions.// If not provided one will be generate but with npm it's easy to end up// with copies of same library and there for copies of the same function// leading to surprises. So just really pick a name that is unique!var isWatchable = // If you call it on any object it will// throw as nothing implements that method yet.//isWatchable({}) // => Exception: method is not implemented // If you define private method on `Object.prototype`// all objects will inherit it.ObjectprototypeisWatchable = { return false;} // => false // Although `isWatchable` property above will be enumerable and there for// may damage some assumbtions made by other libraries. There for it"s// recomended to use built-in helpers methods that will define extension// without breaking assumbtions made by other libraries: isWatchable // There are primitive types in JS that won"t inherit methods from Object: // => Exception: method is not implemented // One could either implement methods for such types:isWatchableisWatchable // Or simply define default implementation:isWatchable // Alternatively default implementation may be provided at creation:isWatchable = // Method dispatches on an first argument type. That allows us to create// new types with an alternative implementations: {}isWatchable // This will make all `Watchable` instances watchable! // => true // Arbitrary objects can also be extended to implement given method. For example// any object can simply made watchable: { return isWatchable} // => true // Full protocols can be defined with such methods:var observers = "observers@" + modulefilenamevar watchers = var watch = var unwatch = watchers watchunwatch // Define type Port that inherits form Watchable {}Portprototype = Object var emit = emit var p = // => info: "hello world"