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'
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.