Some questions about Private Name Objects

David Bruant bruant.d at gmail.com
Mon Aug 27 12:17:41 PDT 2012


Le 27/08/2012 19:54, Matthew Robb a écrit :
> I know this has some serious ugly to it but in the spirit of knowing
> what COULD potentially create the expected behavior, would this not do
> the trick?
>
> var myClass = (function(){
>
>         function myClass(){
>             var __priv = Object.create(this);
>             var __this = __priv.__this = this;
>
>             this.getTest = function(){
If you're willing to have functions as own properties in each instance,
you need the method on the prototype any longer.
If JS engines do their job properly, they will store the function body
once and just create new function objects for each instance (which you
do anyway, so it has no extra cost)

>                return myClass.prototype.getTest.apply((this
> ===__this)?__priv:this, arguments);
>             }
>
>             __priv.test = 0;
>         }
>
>         myClass.prototype.getTest = function() {
>           var __this = this.__this || this, __private = this;
>           return __private.test;
>        }
>
>         return myClass;
>     })(); 

Version with having a function on each instance:

    function myClass(){
        var test = 0;

        this.getTest = function(){
            return test;
        };
    }

No underscore ;-)

Through the different messages we've shared, you've covered the
different ways to do encapsulation and code sharing and the conclusion
is that either you need to add a function to each object (which yield a
linear cost for no reason) or your abstaction leaks if you want to
prototype function to access per-object data. A last alternative is to
associate private data via a WeakMap (it can be shimmed in ES5 with the
same garbage collection properties and with good performances) that
inherited functions all have access to. It works, but it's burdensome
and doesn't read as well as object properties.

David
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120827/56a3b54c/attachment.html>


More information about the es-discuss mailing list