1

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.

asked Oct 2, 2014 at 12:01
2
  • 4
    A lot of that is not nested functions, but nested objects. Commented Oct 2, 2014 at 12:03
  • For the same reason that you can't use this.nestedOne.nestedTwo.nest2() inside your nest method. Commented Oct 2, 2014 at 12:07

2 Answers 2

2

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();

answered Oct 2, 2014 at 12:09
2
  • Hmmm, I don't see anything in the output window, when I click "Run code snippet". Commented Oct 2, 2014 at 19:43
  • Weird, I do - what browser are you on? Commented Oct 2, 2014 at 20:18
0

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();
^^^^
answered Oct 2, 2014 at 12:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.