Symbol is a language feature. As is accessing a property with `[` and `]`. Using the language's features as they were designed is not a hack. And I think we may see your browser's tooling improve when it natively supports ECMAScript 2015, instead of whatever is transpiled today.
Now: Why do you think that properties named by symbols have this special property of being non-enumerable by default? Do you think it is just a coïncidence that it is useful for making a pseudo-private property?
I do not think this particular pattern is a "hack," I think it is one of the use cases that were considered when designing symbols in the first place.
But returning to the purpose of the article, whatever you or I may think of the performance of using closures to create private data, your pattern again supports the article's thesis: By making classes out of functions, objects, and prototypes, we can use the features of the language to extend a class's semantics.
If there was a full-featured monolithic class system like Ruby, we might find that the scoping for methods is not like the scoping for lambdas, and thus we can't just use a closure when we want one.
Your proposed solution leverages the exact same property of JavaScript as TFA.
var Person = function(first, last) {
var serializable = {
first: first,
last: last,
};
...
With Symbol? I guess I just don't see making things more complicated as a positive pattern.What, exactly, is the problem here? I don’t recall the article saying that symbols are the only way to do this, or the best way to do this out of all the options. I recall people saying similar things about closures for a while, until it caught on that closures and lexical scope are a natural part of JavaScript.
TFA’s point is that ECMAScript 2015’s choice to keep classes as first-class functions with prototypes that are objects is what allows us to use all of the techniques we already have for first-class values, including returning them from functions.
As I keep saying, using a closure (if that’s what you want to do) demonstrates the exact same thing, it works because a method is just a function.
Now that we have established that I am not claiming that symbols are better than closures, I will warn you about an edge case: When you use compact method syntax, you do get something that an ordinary function does not provide, the `super` keyword.
I do not know how to make that work in the case where you assign a function to an instance of an object. So if you want to override a function while calling the super-class’s implementation, it might be tricky to use the closure solution.
That being said... I wouldn’t stay up late worrying about it.
let Person = (() = > {
let firstNameProperty = Symbol('firstName'),
lastNameProperty = Symbol('lastName');
return class Person {
constructor (first, last) {
this[firstNameProperty] = first;
this[lastNameProperty] = last;
}
sameFirstName (otherPerson) {
return this[firstNameProperty] == otherPerson[firstNameProperty];
}
};
)();
Now try implementing sameFirstName() using closures. Good luck! :)And it can, since the symbol is just a secret stored in a closure and there are other sorts of secrets. Aside from the "Math.random() + {enumerable: false}" suggestion found elsewhere, you can reproduce the precise[0] semantics of your example using something like:
// Please do not actually write code like this
var Person = (function() {
var names = [];
function Person(name) {
this.key = names.length;
names[this.key] = name;
}
Person.prototype.sameName = function(other) {
return names[other.key] === names[this.key];
};
return Person;
})();
Which is the ES3 generated by this CoffeeScript: class Person
names = []
constructor: (name)->
@key = names.length
names[@key] = name
sameName: (other)->
names[other.key] is names[@key]
Of course these implementations do something dramatically different behind the scenes, and I emphatically don't think people should follow this example, but the interface is the same. Edit: Except that I left `.key` as an editable property, which is problematic. We'll leave that bit as an exercise, though.Whether `names[this.key]` is as "nice" to work with as `this[nameKey]` is, uh, left up to the reader; personally, count me in the camp that doing either of those things is nuttypants compared to `this._name`.
[0]: Assuming that `otherPerson` in your constructor is a typo, of course ;P
Oops, yup. Fixed.
Your solution is pretty clever, though it leaks memory like a sieve. To get around that, you end up needing something like weak maps.
Once you have those, when you do the pattern you suggest, you are basically doing metaprogramming and reinventing the very idea of an "object" yourself from scratch.
That can be fun to do, but to me it starts to feel less like expressing "the same thing" and more like implementing a new language that lets you express the same thing. Just because I can implement a GC in C, that doesn't mean C has a GC. :)
And yet-- is the Symbol approach not metaprogramming? It's clearly a much saner way to shoehorn this feature in, but it's still a shoehorn. And the underlying magic in both cases is in fact simple closure scope, which is really what I wanted to demonstrate.
Edit: And I guess my broader point, to make this more constructive, is that in JS these kinds of idioms live on a continuum of metaprogramming, and for the sanity of your co-contributors you usually want to be doing as little of that as necessary. Like others, I'm wary of presenting something like your example as a "design pattern" without that context.
Edit 2: To illustrate what I mean, I swear to you that if this pattern is adopted widely you will find code like this in the wild:
... = > {
let accountNumberKey = Symbol('accountNumber');
return class Account {
constructor (accountNumber) {
this[accountNumberKey] = accountNumber;
this.accountNumberKey = accountNumberKey; // ??? but transaction log works now
...function Person(first, last){ var firstNameProperty = {}, // unique snowflake obj lastNameProperty = {} // yet another unique obj this[firstNameProperty] = first; this[lastNameProperty] = last; }
ES6 should be saving me from typing all the scoping hacks such as closure. not giving me syntax sugar for things i could do already without odd language constructs (now i have to run TWO loops to get my obj properties. which is what everyone is going to do anyway, since you can iterate on all the symbol properties anyway)
var Person = (function() {
return function(firstName, lastName) {
var privateVars = {
firstName: "",
lastName: ""
};
this.getFirstName = function() {
return privateVars.firstName;
};
this.setFirstName = function(firstName) {
privateVars.firstName = firstName;
return this;
};
this.getLastName = function() {
return privateVars.lastName;
}
this.setLastName = function(lastName) {
privateVars.lastName = lastName;
return this;
};
this.sameFirstName = function(otherPerson) {
return this.getFirstName() == otherPerson.getFirstName();
}
this.setFirstName(firstName);
this.setLastName(lastName);
Object.freeze(this);
return this;
}
}());
var p = new Person("John", "Doe");
var q = new Person("John", "Smith");
var r = new Person("Jane", "Doe");
p.sameFirstName(q); // true
p.sameFirstName(r); // falseMy reaction to the article's approach was largely: okay, cool, this seems approximately as good as the closure-based solution; is there any reason for me to switch? Or is this just a cool toy example to show off classes-as-expressions?
Btw, once a symbol is created, is it ever garbage collected? (They are not in Common Lisp for example).
Possibly on page reload (for javascript in browser) they would. But how about long-running javascript code?
What lessons have folks learned from trying these approaches in other languages? Which is more idiomatic, and why?
I don't get the relucatance to use the language's features rather than hacks (using naming standards and compilers to obfusticate names and then cross fingers) or other hacks (Symbol). Really? You Really want me to write code using Symbol? That's going to be awesome in the debugger. Let's add a watch to "weke30o304_first". Refresh, of shit it's now "gtgrf40r3fe_first", my watches all broke (T_T)
It also makes me sad the `class` spec didn't take that into account so you could use a closure with a `class`.