[Javascript] accessing nested functions

Noah Sussman blinkdog at gmail.com
Sun Jul 8 13:41:48 CDT 2007


On 7/8/07, Pedro Mpa <mail.pmpa at sapo.pt> wrote:
> >var f = new a();
> >var g = new f.b();
> >g.c();
>
> Which is the same as:
>
> var f = new a();
> a.b();
> a.b.c();

I assume you meant

var f = new a();
f.b();
f.b.c();

But in that case the property f.b is a function, not an object.  So
you can't call f.b.c() because f.b doesn't have any properties.

This will work, however:

var f = new a();
new f.b().c();

And suprisingly (to me), the following code will also work:

new new a().b().c();

However, that's sort of silly   ~.^

So it sounds like what you want is to be able to declare an object a
that has a method b that has a sub-method c, and then call c with
a.b.c().  In that case, the problem is not so much with your calling
syntax, but rather with the way you have written your object
constructor.

One approach would be to declare a.b as an object, and give it a
property c, which is a function.  That way you can still call new a()
to get your new object, and it will have the syntax (I think) you
expect:

function a(){
       this.vara = "yourNameHere";

       this.b = {};  //declare b as an empty object

       this.b.varb = "gasFoodLodging";

       this.b.c = function(){
                     this.varc = "eatAtJoes";
                     alert('something');
       }
}

var f = new a();
f.b.c();           //alert: something
alert(f.vara);    //alert: yourNameHere
alert(f.b.varb); //alert: gasFoodLodging

However, notice that there's still no way to access the value of the
method of c named 'varc'.  If you wanted that value, you'd have to
say:

var f = new a();
var g = new f.b.c();
alert(g.varc); //alert: eatAtJoes

Which is again probably not what you wanted.

I suggest you take the advice of Brian L. Matthews:
> google for tutorials about JavaScript's
> brand of OO and read them. JavaScript isn't PHP, and trying to write
> JavaScript as if it's "PHP + nested functions" will surely lead to madness.

Douglas Crockford has written a very in-depth article on public and
private methods in JavaScript, so here is that link to get you
started:

http://javascript.crockford.com/private.html

-- 
Noah Sussman
Noah at OneMoreBug.com



More information about the Javascript mailing list