About private names

Andrew Dupont mozilla at andrewdupont.net
Sat Mar 19 16:41:25 PDT 2011

The recent mention of the private names strawman [1] in the "Standardizing __proto__" thread led me to re-read the proposal. After staring at it for far too long, I had the "aha!" moment, but it left me with a question.

The "Conflict-Free Object Extension Using Private Names" section includes a code example in which a function declares a private name `clone`, uses that private name to define several extensions to built-ins, and then returns the value of the private name so that it can be passed to another scope. The outer scope uses that returned value to set the value of its own private name called `clone`, and is then able to call [].clone, {}.clone, etc., and have them point to the methods that were defined inside the function.

Here's my question: what happens if, sometime after that snippet of code, a user writes code that declares a `clone` property? Something like:

var MyObj = {
 clone: function() {
   return new MyObj(this);

In other words: it appears that, in order to use the `clone` sugar given in the example, a user must "taint" a given scope so that all further references to "clone" (after . or before : at least) will refer to that private name. That's likely not what the user intends. Once a private name is declared in a given scope, can it ever be "reclaimed" as public later on?

Or, to use another example: let's say `MyObj` was defined in a different scope, one in which `clone` was assumed to be a public name. Can I do this...

private clone = installCloneLibrary();
var twin = [{a:0}, {b:1}].clone();
var thing = MyObj.clone(); 

... and have it work the way I intend? In other words, once ES5 fails to find something with the `clone` private name defined on `MyObj`, will it try to find the property with the _public_ name of `clone` before it gives up? (If I'm reading this right, it won't.)

I think it's great that we're trying to find ways to make built-in extension safer without beating the dead horse of namespaces. But I fear that the proposal, in its current form, would be too cumbersome for that purpose.


[1] http://wiki.ecmascript.org/doku.php?id=strawman:private_names

More information about the es-discuss mailing list