Skip to content

Instantly share code, notes, and snippets.

@joseph
Last active August 29, 2015 13:57
Show Gist options
  • Save joseph/9766958 to your computer and use it in GitHub Desktop.
Save joseph/9766958 to your computer and use it in GitHub Desktop.
JS class pattern [2]
// AMD module definition:
define(function (require) {
// An instantiable class:
var K = function () {
this._initialize();
this._p = {};
};
// A "private" method:
K.prototype._initialize = function () {
}
// A public method:
K.prototype.update = function () {
}
// A constant
K.MEANING_OF_LIFE = 42;
return K;
});
@danshultz
Copy link

One final bit of closing that I highly prefer with this pattern, I feel it's easier to grok what is going on and where things live and is actually a bit less levels of indirection...also using var thing = new Thing() explicitly says, I am creating a prototype vs the 'fake' prototype being created of var thing = thing()

Also, I find having to keep track of everything around the following hard to keep track of in my head at times.

K is for Class (and Constants!).
I is for Instance (and Interface!).
P is for Properties (and Private!).

@joseph
Copy link
Author

joseph commented Mar 25, 2014

Well, it is var thing = new Thing() in both cases — that's important. I find that I and P become second nature very quickly — that was definitely true for API and k and p in the old pattern.

I agree that tinkering with private methods in console or via inheritance is great — rarely have we needed truly private methods, and anyway, we have those if we're prepared to pass instance data in as an argument. The "protected" implication of underscore-prefixed methods is reasonably nice (well, gallingly ugly, but nice).

I must admit I don't like your shorthand version because that trailing comma is always a bitch, and especially when you have liberally applied comments to your codebase. Also it's another level of indentation (which is another problem with the first proposal too). And if you are inheriting, you can't use the shorthand, so it's better to have one rule.

I think we can more or less blacklist super — super-free inheritance is still better than our current no-inheritance. If we write small, focused methods it's not a big deal.

Alright, you've swayed me. I'm going to reimplement the Stencil (which is totally changing in the Monocle->Lens transition) in this style then review it.

@joseph
Copy link
Author

joseph commented Mar 25, 2014

Also, you want to read this for getting AMD requires working in a CommonJS way reliably: http://requirejs.org/docs/whyamd.html#sugar

@joseph
Copy link
Author

joseph commented Mar 25, 2014

Oh, I had a confusing typo from my console experiments — see https://gist.github.com/joseph/9766958/revisions. The 'foo' did not belong, it was for testing only.

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