@paulio/embed-js
v0.1.0
Published
P104: Replicating Go struct embedding.
Readme
P104: Embed
Minimalist function for replicating Go struct embedding.
Embedding is a form of polymorphism and an alternative to both inheritance and mixins. I'd say the approach lies somewhere between inheritance and mixins in terms of flexibility, complexity, and error proneness.
API Documentation is in /src.
Import from NPM
package.json
{
"dependencies": {
"@paulio/embed-js": "0.1.0"
}
}my-script.js
import embed from '@paulio/embed-js'
// ...Copy & Paste Code
Copy & paste files from /src into your project. Tests are written in Jest but should be easy to adapt or rewrite for whatever testing framework.
Simple Example
A more detailed example can be found at ./examples/Example.js.
import embed from '@paulio/embed-js'
// A class with methods to be embedded.
class WithName {
_name = ''
getName() {
return this._name
}
setName(name) {
this._name = name
}
}
// A class with getter and setter to be embedded.
class WithAge {
_age = 64
get age() {
return this._age
}
set age(v) {
this._age = v
}
}
// Derived class.
class Person extends embed(WithName, WithAge) {
constructor(name, age) {
this.setName(name)
this.age = age
// or
// this.WithName.setName(name)
// this.WithAge.age = age
}
// ...
}
const person = new Person('Oliver', 24)
person.setName('Bob')
person.age = 42
console.log(person.getName(), person.age)