On Jun 10, 5:05 am, PragueExpat <[EMAIL PROTECTED]> wrote:
> I posted this in comp.lang.javascript also, but would like to hear
> from the jQuery group.

Multi-posting is not liked:

<URL: 
http://groups.google.com.au/group/comp.lang.javascript/browse_frm/thread/2bcf87cb39f60d20/ad1c65a2cbedaa0d?hl=en#ad1c65a2cbedaa0d
>


>
> I (think) that I've come up with a pattern that I haven't seen in any
> publications so far and I would like some feedback. Basically, I was
> looking for a way to inherit private functions and I came up with
> this:
>
> //base private object constructor
>
> function priv(){
>     this.a = 1;
>     this.b = 2;
> }

That doesn't create any "private" variables, a and b will be public
properties of the object returned when new priv() is called.  It is
also customary for constructor names to start with a capital letter,
so:

function Priv(){ ... }

>
> //private object constructor that inherits from base private object
>
> function priv2(){
>     this.c = 3;
>     this.d = 4;}
>
> priv2.prototype = new priv();

It doesn't inherit anything from Priv, it inherits from
priv.prototype.


> //constructor that uses private object in private namespace
>
> function ob(){
>     var _ = new priv2();
>     return {
>         go:function(){
>             alert(_.a);
>         }
>     }
> }
>
> var test = new ob();

A pointless use of new since ob() returns a different object to that
referenced by its this keyword.   All of the properties of
priv2.prototype are public, the only "private" variable is _ (a poor
choice of variable name) as a result of the closure.

As you were told in clj, the only effective way to make private
variables in javascript is to use closures.


> //returns 1
>
> test.go();

And this returns foo:

  priv2.prototype.a = 'foo';
  test.go();


> //only go() is public

The point of private variables is that you can only access them via
privileged methods.  Being able to set (or mask) a property using a
public a access method means they aren't displaying the properties
normally attributed to private variables.


> test;

?


> First of all, is this a known pattern? If so, sorry for the redundant
> information. If not, are there any drawbacks that you can see?

Yes, it doesn't do what you think it's doing.

> The
> advantage, as I see it, is that inherited objects can also inherit
> private functions and properties for use.

The "pattern" you've used does no such thing.  The only private
variable created is the one using a closure, which is a well known
pattern.

<URL: http://crockford.com/javascript/private.html >
<URL: http://www.jibbering.com/faq/faq_notes/closures.html >


--
Rob

Reply via email to