stampit API
Search…
Methods
You can add methods (aka functions) to the objects created from your stamps.
1
const Logger = stampit({
2
methods: {
3
debug(str) {
4
console.log(str)
5
}
6
}
7
})
8
9
const logger = Logger()
10
11
logger.debug('Server started')
Copied!
All the methods are attached to object's prototype.
1
logger.__proto__.debug === Logger.compose.methods.debug
Copied!
Moreover, the entire methods descriptor metadata becomes the prototype.
1
logger.__proto__ === Logger.compose.methods
Copied!
If you compose the stamp above with any other stamp, then object instances created from it will also have the .debug method.
1
const Server = Logger.compose({
2
methods: {
3
async start() {
4
this.debug('Server started')
5
}
6
}
7
})
8
9
const server = Server()
10
11
server.debug('Starting server')
12
server.start()
Copied!

Descriptor merging algorithm

The methods are copied by assignment. In other words - by reference using Object.assign.
1
Logger().debug === Server().debug
Copied!
In case of conflicts the last composed method wins. To avoid method collision use the @stamp/collision stamp. To make sure a method is implemented use the @stamp/required stamp.
NOTE
When using the @stamp/required stamp it creates a proxy object and returns from the factory. This means that logger.__proto__ === Logger.compose.methods or logger.__proto__.debug === Logger.compose.methods.debug will no longer be true.

Other ways to add methods

Exactly the same stamp can be created in few ways. Here they all are.
1
function myDebug(str) {
2
console.log(str)
3
}
4
5
const Logger = stampit({
6
methods: {
7
debug: myDebug
8
}
9
})
10
11
const Logger = stampit.methods({
12
debug: myDebug
13
})
14
15
const Logger = stampit().methods({
16
debug: myDebug
17
})
Copied!
Last modified 3yr ago