[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.javascript

Accessing private fields in the prototype?

ram

6/6/2015 11:05:00 PM

A /local variable/ of the constructor can be accessed from
within functions that are defined within the constructor.
This can be used to create /private fields/ of objects.

When objects of one constructor share a common method,
this method can be added to the /prototype/ of the constructor,
so that it does not have to be added to every object.

But can this be combined? Can we add a method to the
prototype of the constructor /and/ access /private/ fields
of the object from within this method?

(I see only the possibility to add at least a small
private method to /each and every object/, which then
might use helper method from the prototype.)


1 Answer

Michael Haufe (\"TNO\")

6/9/2015 4:05:00 PM

0

On Saturday, June 6, 2015 at 6:05:32 PM UTC-5, Stefan Ram wrote:
> A /local variable/ of the constructor can be accessed from
> within functions that are defined within the constructor.
> This can be used to create /private fields/ of objects.
>
> When objects of one constructor share a common method,
> this method can be added to the /prototype/ of the constructor,
> so that it does not have to be added to every object.
>
> But can this be combined? Can we add a method to the
> prototype of the constructor /and/ access /private/ fields
> of the object from within this method?
>
> (I see only the possibility to add at least a small
> private method to /each and every object/, which then
> might use helper method from the prototype.)

You can use a method similar to what Andrea Giammarchi used as described in his blog post: http://webreflection.blogspot.com/2010/09/javascript-protected-prope...

There also exist some creative hacks utilizing the "with" statement described here in the past, but I think a slight variation of what was described above is the way to go if you aren't going to use the new ES6 features (classes + Symbol)