Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active August 9, 2019 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericelliott/3c7e1c130b11c79f65b8 to your computer and use it in GitHub Desktop.
Save ericelliott/3c7e1c130b11c79f65b8 to your computer and use it in GitHub Desktop.
Initializing private data with Stampit

Working with Stamps: How to Initialize Private Data

A common question to people new to stamps is "what's the right way to initialize private data with stamps?"

One of the problems with constructor functions is that they frequently conflate instantiation and initialization. That's fine if you're inheriting from a single source, but it gets problematic if you try to compose multiple ancestors. How do you pass data to your initializing functions without creating argument conflicts between ancestors?

There are actually several different options, but the one I consider to be the best is to separate initialization from instantiation. In other words, you set the stamp's private state after the object is created.

This affords the least opportunity for stamps to collide with each other in incomatible ways when you compose them. The best stamps have self-describing API's, and compose easily with other stamps.

In this example, we have a private variable called name, along with a getter / setter called .name().

var f = stampit().enclose(function() {
  var name;

  return stampit.mixIn(this, {
    // Getter and setter for name:
    name: function (value) {
      if (value) {
        name = value;
        return this;
      }
      return name;
    }
  });
});

// f() instantiates and returns the instance.
// .name('foo') initializes the private variable.
var thing = f().name('foo'); 
thing.name(); // 'foo'
@AHaliq
Copy link

AHaliq commented Aug 9, 2019

Is there an updated post on private variables and providing setters and getters to them? I'm getting an 'enclose is not a function' error from this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment