brinch
brinch

Reputation: 2614

Nested JavaScript functions

I would like to make nested JavaScript functions as a prove of concept. I found an example and modified it a little to fit my prove of concent:

var t = {
    nestedOne: {
        nest: function() {
            alert('nest');
            this.nestedTwo.nest2();
        },
        nest3: function() {
            alert('nest3');
        },       
        nestedTwo: {
           nest2: function() {
              alert('nest2');
              t.nestedOne.nest3();
           }       
        }
    }
};

t.nestedOne.nest();

// *** Output is nest, nest2 and nest3 ***

This works, but I wonder why in nest2, I have to call by t.nestedOne.nest3, and not this.nestedOne.nest3, similar to how I call from nest2.

Upvotes: 1

Views: 77

Answers (2)

Jamiec
Jamiec

Reputation: 136104

Its all about the context of this

The easiest way to explain, is to make a slight change to your code:

var t = {
    nestedOne: {
        nest: function() {
            console.log('nest',this);
            this.nestedTwo.nest2();
        },
        nest3: function() {
            console.log('nest3',this);
        },       
        nestedTwo: {
           nest2: function() {
              console.log('nest2',this);
              t.nestedOne.nest3();
           }       
        }
    }
};

t.nestedOne.nest();

The output from the above is

nest Object { nestedTwo={...}, nest=function(), nest3=function()}
nest2 Object { nest2=function()}
nest3 Object { nestedTwo={...}, nest=function(), nest3=function()}

Note that in the second call, this refers to the function, no longer the object.

Now, you can make the following 2 changes

  • call next2 passing in the context of this: this.nestedTwo.nest2.call(this);

  • use this in nest2: this.nest3();

And all works as expected:

var t = {
    nestedOne: {
        nest: function() {
            console.log('nest',this);
            this.nestedTwo.nest2.call(this);
        },
        nest3: function() {
            console.log('nest3',this);
        },       
        nestedTwo: {
           nest2: function() {
              console.log('nest2',this);
              this.nest3();
           }       
        }
    }
};

t.nestedOne.nest();

Upvotes: 2

Quentin
Quentin

Reputation: 943480

The context of a function call is determined by the object on which the function is called, not the left-most object in the path used to get to it.

this:

this.nestedTwo.nest2();
     ^^^^^^^^^

not this:

this.nestedTwo.nest2();
^^^^

Upvotes: 0

Related Questions