stampit API
  • Introduction
  • Essentials
    • What is a Stamp
    • Installation
    • Specification
      • Merging algorithm
      • Object creation internals
    • FAQ
  • API
    • Quick start
    • Basics
    • Methods
    • Properties
    • Deep properties
    • Initializers
    • Static properties
    • Static deep properties
    • Configuration
    • Deep configuration
    • Composers
    • Property descriptors
    • Static property descriptors
    • Name
  • Ecosystem
    • Ecosystem Overview
    • @stamp/collision
    • @stamp/required
    • @stamp/privatize
    • @stamp/named (DEPRECATED)
    • @stamp/instanceof
Powered by GitBook
On this page
  • Descriptor merging algorithm
  • Other ways to add methods
  1. API

Methods

PreviousBasicsNextProperties

Last updated 7 years ago

You can add methods (aka functions) to the objects created from your stamps.

const Logger = stampit({
  methods: {
    debug(str) {
      console.log(str)
    }
  }
})

const logger = Logger()

logger.debug('Server started')

All the methods are attached to object's prototype.

logger.__proto__.debug === Logger.compose.methods.debug

Moreover, the entire methods becomes the prototype.

logger.__proto__ === Logger.compose.methods

If you compose the stamp above with any other stamp, then object instances created from it will also have the .debug method.

const Server = Logger.compose({
  methods: {
    async start() {
      this.debug('Server started')
    }
  }
})

const server = Server()

server.debug('Starting server')
server.start()

Descriptor merging algorithm

The methods are copied by assignment. In other words - by reference using Object.assign.

Logger().debug === Server().debug

NOTE

Other ways to add methods

Exactly the same stamp can be created in few ways. Here they all are.

function myDebug(str) {
  console.log(str)
}

const Logger = stampit({
  methods: {
    debug: myDebug
  }
})

const Logger = stampit.methods({
  debug: myDebug
})

const Logger = stampit().methods({
  debug: myDebug
})

In case of conflicts the last composed method wins. To avoid method collision use the stamp. To make sure a method is implemented use the stamp.

When using the 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.

@stamp/collision
@stamp/required
@stamp/required
descriptor metadata